By using this site you agree to the use of cookies.

Learn more

Share via:

Check if string contains a substring with PHP

Check if a string contains a substring using strpos and regular expressions.

Edited: 2016-04-09 10:29

Checking if a source string contains a given substring, such as certain words or phrases, is commonly done using the native strpos function of PHP, but it is also possible to check for the existence of a substring through the use of regular expressions.

This is also known as the needle in haystack problem, a figure of speech used to describe the situation. The source string is the haystack, and the substring is the needle to be found.

A common use case is for e-mail validation, where strpos is used to check if a user-entered e-mail on a website contains a "@" character, which is required. This is, however, not quite enough to ensure that an e-mail address is valid, but it does provide basic validation, which is often sufficient to avoid obvious mistakes and fake e-mail adresses being submitted.

Using strpos

The strpos function will either return false if substring is not found, or a numeric value representing it's position if it is found. This is why we use the "!==" operator, which loosely means "not equal to". A value of "0" would also be understood as false, so doing a "!=" comparison will not work. The "!==" operator will however, as it makes PHP do an an exact comparison.

Note. Again. If $substring is found in $source_str, and it is located in the beginning (the 0'th position), it will return this position. Hence we use "!==" or "<>" as the comparison operator:

$source_str = '';
$substring = '@';

if (strpos($source_str, $substring) !== false) {
  echo 'Found it';
} else {
  echo "Not found!";

Note. Use stripos for a case-insensitive version of strpos.

Using regular expressions

Regular expressions can be used to match more than just a string, and is generally used when one wants to match a pattern contained within a source string, and not just for simple parts. To use a regex we can use the preg_match function.

Below is a very simple match, which can also be performed using stripos:

if (preg_match("/neeDle/i", "There's a small needle in a haystack")) {
    echo "Found!";
} else {
    echo "Not found!";