Just use the function strpos
(or mb_strpos
to strings non ASCII):
$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 it is found, its numeric position.
Note that if string is found at the beginning of the line, the return will be 0
, so we have to use type comparison ( ===
or !==
) to differentiate false
of 0
.
Other syntax examples:
$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 working with variable data, it is best to ensure 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 avoid having 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 at the "ends" of the two strings, looking for ,moto,
within ,carro,ciclomotor,
and eliminating ambiguities, without having to call for more complex functions.
stripos ()
As well remembered by @DanielOmine , if you want to find the words regardless of whether they are in uppercase or lowercase letters, you can use the functions case insensitive stripos()
and mb_stripos()
(several PHP functions have version with and without i , which is just insensitive ). It is worth noting that these internal functions are limited in relation to accentuation.
Using DB
If this data is coming from a database, you can filter it directly into SELECT
, we have some examples here on the site.