How To Check If String Contains A Specific Word in PHP? – POFTUT

How To Check If String Contains A Specific Word in PHP?


I have a string and want to check if the string provides some word I want to look. For example the string is like below

$mypoem="This is a poem from poftut.com to its readers";

There are different way to archive this we will look them below.

By Using strpos() Function

strpos is a Php function used to find given word position in a string. If the word exist strpos will return the the start position of the word in the string if not it will return -1 . In this example we will look string poem in the string variable $mypoem.

$mypoem="This is a poem from poftut.com to its readers";

if (strpos($mypoem, 'poem') !== false) {
 echo 'true';
}

By Using preg_match() Function

preg_match is a regular expression match and gives more details to check. We can look complex words but for now we just look simple word match. In this example we will look string poem in the string variable $mypoem.

$mypoem="This is a poem from poftut.com to its readers";

if (preg_match('/poem/',$mypoem))
 echo 'true';

 

How To Check If String Contains A Specific Word in PHP? Infografic

How To Check If String Contains A Specific Word in PHP? Infografic
How To Check If String Contains A Specific Word in PHP? Infografic

LEARN MORE  How To Convert String To Int (Integer) In Java?

Leave a Comment