php logo on purple background

PHP: How to check if a string contains a specific word?

Written by

in

When working with strings in PHP, you can already use many handy functions to manipulate the string contents. Sometimes you only want to check for the string contents before doing an action.

You can check if a string contains a specific word in PHP by using the strpos(), preg_match() or str_contains().

Using strpos()

The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found, it returns false. You can use this function to check if a string contains a specific word as follows:

PHP
$string = "This is a sample string.";
$word = "sample";

if (strpos($string, $word) !== false) {
    echo "The string contains the word.";
} else {
    echo "The string does not contain the word.";
}

In this example, we first define a string $string and a word $word. Then, we use the strpos() function to check if the $string contains the $word. If the $word is found in the $string, the function will return a position value that is not false, and the output will be “The string contains the word.” Otherwise, the function will return false, and the output will be “The string does not contain the word.”

Using preg_match()

The preg_match() function searches a string for a pattern and returns true if the pattern is found, and false otherwise. You can use this function to check if a string contains a specific word as follows:

PHP
$string = "This is a sample string.";
$word = "/sample/";

if (preg_match($word, $string)) {
    echo "The string contains the word.";
} else {
    echo "The string does not contain the word.";
}

Using str_contains()

The str_contains() method is available in PHP 8 and higher versions. You can use this method to check if a string contains a specific word as follows:

PHP
$string = "This is a sample string.";
$word = "sample";

if (str_contains($string, $word)) {
    echo "The string contains the word.";
} else {
    echo "The string does not contain the word.";
}

Performance Comparison

When comparing the performance of those three methods, we get the following result:

strpos()1.37e-7 seconds = 0.137 micro seconds
preg_match()1.54e-7 seconds = 0.154 micro seconds
str_contains()1.28e-7 seconds = 0.128 micro seconds

So the new method str_contains() (for PHP 8.0 or higher) is the fastest one.

For the results, the mean execution time in a loop with 1,000,000 cycles was calculated for each method.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *