Consider:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')
?
Consider:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')
?
You can use the
strstr
function:Without using an inbuilt function:
The strpos function works fine, but if you want to do
case-insensitive
checking for a word in a paragraph then you can make use of thestripos
function ofPHP
.For example,
Find the position of the first occurrence of a case-insensitive substring in a string.
If the word doesn't exist in the string then it will return false else it will return the position of the word.
The function below also works and does not depend on any other function; it uses only native PHP string manipulation. Personally, I do not recommend this, but you can see how it works:
Test:
Look at
strpos()
:Here is a little utility function that is useful in situations like this
I'm a bit impressed that none of the answers here that used
strpos
,strstr
and similar functions mentioned Multibyte String Functions yet (2015-05-08).Basically, if you're having trouble finding words with characters specific to some languages, such as German, French, Portuguese, Spanish, etc. (e.g.: ä, é, ô, ç, º, ñ), you may want to precede the functions with
mb_
. Therefore, the accepted answer would usemb_strpos
ormb_stripos
(for case-insensitive matching) instead:If you cannot guarantee that all your data is 100% in UTF-8, you may want to use the
mb_
functions.A good article to understand why is The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky.