How to check if a string contains another string in PHP

Apr 7, 2011

help with php

This post is another quick explanation on something that is is much more difficult to figure out than it should be. One of the most basic things you would ever want to do in programming is check if one string of text contains another string of text. In every other programming language I can think of this is simple but for some reason the PHP way of doing this has added complexity.

Lets see some code then, remember the triple equals as it’s important.

$position_in_string = strpos($string_you_are_searching, $searching_for_this);
if($position_in_string === false) {
   // Not found
} else {
   // Found

This seems crazy to me and I would much prefer to check for the positive result of the search. In many languages then null, false or -1 would be returned and we could check using a much more palatable condition. This is what I normally do when I write in other languages so I almost always get caught out in PHP with one of the following.

$position_in_string = strpos($string_you_are_searching, $searching_for_this);
if ($position_in_string > -1) {
   // Always true

// check for null or false
if(strpos($string_you_are_searching, $searching_for_this)) {
   // Always true, or always false - i forget, but neither is useful!

This all stems from two features of PHP, the ability to return different types from a function depending on the success of the function and PHPs equals operators. First of all, returning false from a function that fails is a really useful feature of a dynamically types language but it is often confusing – so you need to be careful to remember that the return from strlen is either a number indicating the position of the match or is false.

Most languages have two equals operators and we are all familiar with using a single equals to assign a variable and a double equals to compare. PHP has a triple equals that is an identity operator which checks if the values have the same value AND are of the same type. So if you compare a float of value 99.0 to an integer of value 99 to a string “99” they are all considered different.

So remember – check if the return is === false and then you have the negative condition, so a simple else clause allows you to do your stuff.