Check if a string contains a specific word or not in PHP
In this article, we are going to see how to check if the occurrence of a specific word in a string using PHP. It can be done by matching the search string with the source string.
What are the methods for checking a specific word in a string?
There are several methods to check if a string contains a specific word or not in PHP. Below are the two methods:
- Using String function
- Using the traversal method and etc.
Let us first discuss the simplest one i.e. using String function,
<?php
$str = 'Codespeedy Codes faster and also in efficient manner';
$s='Codes';
if (strpos($str,$s) !== false) {
echo '"'.$s.'" Present in the source string';
}
?>Explanation:-
The function strpos() checks the search string($s) in the source string($str). If it is found, it returns true.
Output:-
"Codes" Present in the source string
Let us discuss another method for finding specific string i.e. the traversal method,
Check if a string contains a specific word or not in PHP
<?php
$str='Codespeedy Codes faster and also in efficient manner';//source string
$s='Codes';//finding string
$i = $m = $c =$flag=0;
while ( !empty($str[$c]))
{
if ( $str[$m] == $s[$i] )
{
$i++;
$m++;
if ( empty($s[$i])) //Find occurance
{
echo $s.' is present in '.($c+1).' location<br>';
$flag=1;
$i=0;
$c=$m;
}
}
else //... mismatch
{
$c++;
$m = $c;
$i=0;
}
}
if($flag==0)
echo $s.' is not present';
?>
Explanation:-
In the above code segment, every character in the search string($s) is compared with every character of source string($str). Both are incremented and compared until the $s is empty. If there is a mismatch then the $s again starts comparing its character from the beginning. If the $s is empty, then the string is found.
Output:-
Codes is present in 1 location Codes is present in 12 location
There are also other ways to find a string in the source string using PHP. If you have any doubts about the above topic, leave us a comment below.
See also,
Leave a Reply