Check if a string contains a specific word in PHP?

In this tutorial you will find various techniques that check for substrings, character strings or special characters that exist in other strings.

To determine whether a string contains an exact specific word, we can use a simple PHP function called strpos().



The first parameter is for the whole string, the second parameter find is for the first occurrence of that specific word and the last one start is an optional parameter. So below is the PHP example:

	$main_string = 'you are welcome';
	$search_string = 'are';

	if (strpos($main_string, $search_string) !== false) {
    		echo "matched";


But keep in mind, as PHP strpos() returns the offset of the search string or return false if no occurrence, != false or === true will not going to work. So we need to use !== false.

But if the main string contains “area”, “hare” then it will not going to work. Because “are” is present in the word “area”. So we need to use PHP regular expression for that. Below is the example of a regular expression by which you can check if a string contains a specific word:

function isWordPresent($main_string, $search_string)
    	if (preg_match('/\b'.$search_string.'\b/', $main_string)) {
    		return true;
		return false;

But preg_match is slower than strpos() 3x times.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment