How to check if a string contains a specific word in PHP
Last Updated on Dec 20, 2022 - Written By Torikul Islam
In this article, I provided some example and brif explanation below.
Basic syntax
if (strpos('string', 'specific_word') != false){ echo 'true';}
str_contains('string', 'specific_word'){ echo 'true';}
We need to provide two parameters.
1. String: The first parameter should contain the string from where you want to find out the word.
2. Specific_word: In this parameter you should put a specific word which you want to find out from the string.
Note: In the placement of parameters, you can use PHP variables.
Discussion and example: check string for a specific word
You should keep in mind that !== false, != false, === true, == true won’t give you the same result.
The function strpos() returns either the offset or the boolean false if the needle isn't found. As 0 is a valid offset and 0 is "falsey", you can't use simpler constructs like !strpos($string, 'word'). You can avoid this issue by always using strpos($string, 'word') > -1 to test for true.
Example 1:
<?php
//input string
$string = 'Here is my example string';
//checking string
if (strpos($string, 'example') != false){
echo 'true';}
else{ echo 'false';}
?>
Output:
true
Example 2:
<?php
//input string
$string = 'Here is my example string';
//checking string
if (strpos($string, 'ample') != false){
echo 'true';}
else{ echo 'false';}
?>
Output:
true
This even showing the output ‘true.’ But why? In this string, there is no word ‘ample.’
If you are looking specifically for the word ‘ample’, then you need to check if there is a character or a space before and after the word.
Example 3:
<?php
//input string
$string = 'Here is my example string';
//checking string
if (strpos($string, ' ample ') != false){
echo 'true';}
else{ echo 'false';}
?>
Output:
false
Note: The both strpos() and str_contains() are case sensitive function.
Example 4:
<?php
//input string
$string = 'Here is my Example string';
//checking string
if (str_contains($string, ' example ')){
echo 'true';}
else{ echo 'false';}
?>
Output:
false
It returns the result false, because of case sensitiveness.