PHP

[Solved – 10 Answers]How to check if a string contains a specific word in PHP


In this sample code:

php code
$a = 'How are you?'; 
if ($a contains 'are') 
echo 'true'; 

How to write the statement in a proper way
If ($a contains ‘are’)?

  • The strpos (http://php.net/manual/en/function).strpos. php function is used to find the occurrence of one string inside other:
php code
$a = ‘hello everyone?';
 if (strpos($a, ‘hello') !== false)
 { 
echo 'true';
 } 

Note :
The usage of !== false is deliberate; strpos returns either the offset at which the needle string begins in the haystack string, or the Boolean false if the needle isn’t found. Since 0 is a valid offset and 0 is “falsey”, we can’t use simpler constructs like !strpos($a, ‘hello’).

  • Here is the another function to check whether the string contains specific word in php.
php code
// returns true if $needle is a substring of $haystack function contains($needle, $haystack)
{ 
  return strpos($haystack, $needle) !== false; 
} 

  • To determine whether a string contains another string Here is the another way of using PHP function strpos().
    int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
php code
<?php $haystack = 'how are you'; 
$needle = 'are'; 
if (strpos($haystack,$needle) !== false) 
{
 echo '$haystack contains $needle';
 }
 ?> 
Note :

  • If the needle function given in the beginning of the haystack it will return position 0, if we compare
    a == compare then it won’t work,we need to do a ===.
  • a == sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.
  • a === sign is a comparison to see whether two variables / expressions / constants are equal and have the same type – i.e. both are strings or both are integers.
See also  [Solved - 4 Answers] PHP - Saving image from PHP URL

  • Here is the another way of using strpos() function:
php code
<?php $mystring = 'abc'; 
  $findme = 'a';
  $pos = strpos($mystring, $findme); 
  // because the position of 'a' was the 0th (first) character. 
  // Note our use of ===. Simply, == would not work as expected   
  if ($pos === false)
  { 
  echo "The string '$findme' was not found in the string '$mystring'.";
  } 
  else 
  { 
  echo "The string '$findme' was found in the string '$mystring',"; 
  echo " and exists at position $pos."; 
  } 
?> 

  • Use case-insensitve matching using stripos():
php code
if (stripos($string,$stringToSearch) !== false) 
{
 echo 'true'; 
} 

  • To avoid “falsey” and “truthy” problem, use substr_count:
php code
if (substr_count($a, 'are') > 0)
 { 
echo "at least one 'are' is present!";
 } 
  • Compare to strpos it’s a bit slower only, but this function avoids the comparison problems.

  • Here is the another new function called strstr() function. The sample code is given below:
php code
if (strlen(strstr($haystack,$needle))>0)
 { 
// Needle Found
 } 
Note:
The strstr() function is case-sensitive. For a case-insensitive search, use the stristr() (http://www.php.net/manual/en/function.stristr.php) function.

  • Don’t use preg_match() for every cases, In some cases like if we need to check whether one string is contained in another string use strpos() or strstr() instead of preg_match()
  • The strpos() or strstr() functions are faster than preg_match()(http://in2.php.net/preg_match)
php code
if (strpos($text, 'string_name') !== false)
{
 echo 'get the string';
 } 


It can be done in three different ways:

php code
$a = 'How are you?'; 

1- stristr()

php code
if (strlen(stristr($a,"are"))>0)
 {
 echo "true"; // are Found
 } 

2- strpos()

php code
if (strpos($a, "are") !== false)
 { 
echo "true"; // are Found
 } 

3- preg_match()

php code
if( preg_match("are",$a) === 1) { 
echo "true"; // are Found
 }

  • If we need to check if the string contains several specifics words, Simply use the below code:
php code
$badWords = array("dette", "capitale", "rembourser", "ivoire", "mandat"); $string = "a string with the word ivoire";
 $matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $string, $matches); 
if ($matchFound) 
{
 echo "a bad word has been found";
 }
 else
 { 
echo "your string is okay";
 } 

About the author

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment

X