PHP: Check if a string contains another string or substring

As a web site templating language, string processing is what PHP is good at. There’s always a chance that you need to verify and make sure if a string contains another string. For example, to check if an at sign is included in the entered email address by a visitor:

if (strpos($_POST['email'], '@') !== false) {
    echo 'The email address has @ in it.';
}

Technically, strpos() function returns the index location of the first character of the specified substring if it finds it. If it fails in locating the substring in the string, it returns boolean false. As it’s possible that the substring may start in the very beginning of the father string thus strpos() returning 0 which is interpreted as false in PHP, a absolute comparison of !== is required.

2 thoughts on “PHP: Check if a string contains another string or substring”

  1. What if there are 100,000+ strings to check? Anyway to check them for a string at the same speed as fileexists()?

Comments are closed.

Scroll to Top