Categories
PHP Tips & Tutorials

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.

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.

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

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.