How to Find if a String Contains a Word in PHP
The strpos()
function finds the first occurrence of a string inside another string in PHP. It is a case-sensitive function that returns the index of the first character of a string if a match is found and false
if no matches are found.
Let's try out a basic example of looking for a string in a string using strpos()
:
$str = 'This is some text.';
$result = strpos($str, 'some');
print_r($result);
8
As expected strpos()
returns 8
as the position of the substring "some" in the example above.
strpos()
can be used to check whether a string contains a specific word and do something as a result with a conditional if
statement:
$str = 'This is some text.';
$result = strpos($str, 'text');
if ($result !== false) {
print_r($result);
} else {
print_r('No result do something else.');
}
13
Set a Start Position for strpos()
An optional third argument can be used with strpos()
to specify an index to begin searching from.
$str = 'This is some text.';
$result = strpos($str, 'This', 8);
if ($result !== false) {
print_r($result);
} else {
print_r('No result do something else.');
}
No result do something else.
Conclusion
For old versions of PHP the stripos()
function can be used to achieve the same results as strpos()
though it is slower.