Just use the function strpos
(or mb_strpos
for strings non-sascii):
$palheiro = 'canais,proteses,implantes';
$agulha = 'proteses';
$pos = strpos( $palheiro, $agulha );
// exemplo de uso:
if ($pos === false) {
echo 'Não encontrado';
} else {
echo 'Encontrado';
}
The function strpos
returns false
when the string is not found, and if found, its numerical position.
Important to note that if the string is found at the beginning of the line, the return will be 0
, so we have to use type comparison ( ===
or !==
) to differentiate the false
of 0
.
Other examples of syntax:
$encontrado = ( strpos( $palheiro, $agulha ) !== 0 );
if ($encontrado) {
echo 'Encontrado';
} else {
echo 'Não encontrado';
}
$pos = strpos( $palheiro, $agulha );
if ( $pos !== false) echo 'encontrei!';
$pos = strpos( $palheiro, $agulha );
$encontrei = ( $pos !== false ) ? 'sim' : 'não';
Tips:
If your application is to work with variable data, it is best to secure and use a format that does not give side effects if you have similar words.
For example:
$palheiro = 'carro,moto,ciclomotor';
$agulha = 'moto';
// encontrado!
$palheiro = 'carro,ciclomotor';
$agulha = 'moto';
// encontrado! Opa! Peraí???
This is because the word "moped" contains "motorcycle".
The solution:
To not need to use more complex functions, just use a little trick:
$palheiro = 'carro,moto,ciclomotor';
$agulha = 'moto';
$pos = strpos( ','.$palheiro.',', ','.$agulha.',' );
// encontrado!
$palheiro = 'carro,ciclomotor';
$agulha = 'moto';
$pos = strpos( ','.$palheiro.',', ','.$agulha.',' );
// não encontrado!
The explanation is simple: adding the commas on the "tips" of the two strings, crunching ,moto,
inside ,carro,ciclomotor,
and eliminating ambiguities, without needing to appeal to more complex functions.
strips()
As well remembered by @Danielomine, if you want to find the words regardless of whether they are uppercase or lowercase, you can use the functions case insensitive stripos()
and mb_stripos()
(various functions of PHP have version with and without the i, which is precisely from insensitive). Note that these internal functions are limited in relation to accentuation.
Using with DB
If this data is coming from a database, you can filter this directly into the SELECT
, we have some examples here on the site.