Signup/Sign In
LAST UPDATED: AUGUST 4, 2021

How to Check If a String Contains a Specific Word in PHP?

Answer: Using strpos() function

The strpos() is a built-in function in PHP. This function is used to find the position of the first occurrence of a string inside a string.

With the help of this function, we can check whether a string contains a specific word or not. This function returns the position of the first occurrence of a string. If the string is not present inside another string, then this function returns false.

The position of the string starts with 0 instead of 1.

Example: Check If a String Contains a Specific Word

In the given example, we have checked whether the word language is present inside the existing string strpos() function.

<!DOCTYPE html>
<html>
<head>
	<title>strpos() function</title>
</head>
<body>
	<?php
	$str1 = "language";
	$str2 = "PHP is a general-purpose scripting language";
	if(strpos($str2, $str1) !== false){
	    echo "Word Found!";
	} else{
	    echo "Word Not Found!";
	}
	?>
</body>
</html>

Output:


Word Found!

The strpos() function is case sensitive such as if we try to check out whether the word "Language" is present inside the string or not, but the existing word is a "language," then this function returns false or "word not found."

Example 2: Check If a String Contains a Specific Word

As we have discussed above that the strpos() is case-sensitive so we have tried to find the word whether the word Language is present within the existing string or not. The output is "Word Not Found!" even when the word "language" is present in the string. This is because we have specified uppercase "L" instead of lower case "l".

<!DOCTYPE html>
<html>
<head>
	<title>strpos() function</title>
</head>
<body>
	<?php
	$str1 = "Language";
	$str2 = "PHP is a general-purpose scripting language";
	if(strpos($str2, $str1) !== false){
	    echo "Word Found!";
	} else{
	    echo "Word Not Found!";
	}
	?>
</body>
</html>

Output

As we can see, the output is "Word Not Found!", this is because the function strpos() is case-sensitive.


Word Not Found!

Conclusion

In this lesson, we have discussed how to check if a string contains a specific word in PHP. To check if a string consists of a particular word, PHP offers an in-built function named strpos(). This function takes two arguments as its value, the first argument is the string, and the second argument is the word that we want to check whether it is present within the string or not. If the word is present within the string, then this function returns true otherwise, it returns false.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.