We consider that the variable $foo
contains a string with value hello world . My question is: how could one check if it $foo
contains the word world and throw a echo
?
$foo = 'Hola mundo';
if($foo contiene 'mundo') {
echo 'True';
}
We consider that the variable $foo
contains a string with value hello world . My question is: how could one check if it $foo
contains the word world and throw a echo
?
$foo = 'Hola mundo';
if($foo contiene 'mundo') {
echo 'True';
}
You can do this with the function
strpos
, which allows you to find the position of the first occurrence of a substring in a string, that is, the position of the first occurrence of a string within another string.If the position is not found, it will return
false
.Error404's answer is the best (use
strpos
,stripos
orstrstr
), as an alternative I'm going to suggest using regular expressions andpreg_match
that it can be useful in other cases (for example if you need to search for some pattern more than a specific string) and that, although it will work in your case particular, is not recommended because it will be slower.So you could do something like:
Another option would be to use the function strstr(String string,String search) finds the first occurrence of a string within another string , If it finds the value sought, it will be that the value returned, otherwise it will return an empty string. To all this applying the function strlen(String string) to obtain the length of the string (if it is greater than 0 it is found)
The above function is case sensitive, if you want it to not matter, use the function stristr(String string,String search)
The
stripos
,strpos
and functionsstrstr
are used to find substrings .For example, they would find the word
"la"
inside"hola mundo"
.If you are looking for words , you must check that there are no alphanumeric characters before and after the word. Using regular expressions, the assertion
\b
matches at these positions.Demo: http://ideone.com/W8OJG5
Just be aware that
$palabra
it shouldn't have any of the following regex metacharacters, and might fail if it did.This is a secure version:
And, to know in which position the word is found:
Demo: http://ideone.com/7Jh4nX
Update 2022 and PHP 8.
Another alternative is to use str_contains() (PHP 8.0+). See specification .
You can work directly with multibyte , so version is not needed
mb_*
It is case sensitive , so do the previous conversions if necessary.