}

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

Created:

Introduction

In this tutorial we explain the proper way to search a string with php.

$test = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. ';

We will explain how to search on $test variable.

Using strpos

PHP has the standard function strpos.

Here is an example on how to use it:

if (strpos($test, 'dolor') !== false) {
    echo 'true'; 
}

strpos returns either the offset at which the string begins, or the boolean false if the needle isn't found (0 could be a position).

Using regular expressions

Another approach is to use regular expressions, using the preg_match function. Here is an example:

if (preg_match('/dolor/', $test)) {
    echo 'true'; 
}

If you compare the performance of preg_match against strpos, the later is faster. However preg_match is input is a regular expression and it should be expected to be slower.

Custom function

This is optional, but if you don't like how strpos is used or the name of the function, you can create a custom function with the name contains. Here is the function contains, which uses strpos:

function contains($needle, $haystack) { 
    return strpos($haystack, $needle) !== false; 
}