PHP: Check if a string contains another string or substring

by Yang Yang on April 23, 2009

Share This Article:
Subscribe to Kavoir: blog feed

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.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 2 comments… read them below or add one }

Stuart June 6, 2009 at 4:31 pm

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

Reply

ja November 23, 2009 at 10:11 pm

thanks!!!

Reply

Leave a Comment

Previous post:

Next post: