PHP - Check if a string contains a substring

(1 vote, average 5.00 out of 5)

In many object-oriented languages, you often want to check for the presence of a substring in a string. PHP does not contain a .contains() method which you can use, but you can create your own using the strpos() function quite easily:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Checks to see of a string contains a particular substring
* @param $substring the substring to match
* @param $string the string to search 
* @return true if $substring is found in $string, false otherwise
*/
function contains($substring, $string) {
        $pos = strpos($string, $substring);
 
        if($pos === false) {
                // string needle NOT found in haystack
                return false;
        }
        else {
                // string needle found in haystack
                return true;
        }
 
}

Although this function is not very complex, it can simplify your code by reducing statements like if (strpos($str, $substr) == -1) to simply if (contains($str, $substr).

Partner Links:
Last Updated on Saturday, 17 July 2010 23:49  
Related Articles

» PHP - Read in a file

The following function demonstrates how to read in a local file with PHP. You must first use the function to open the file handle. This tells PHP where to look to find this file. After that, it is simply a matter of iterating over the file until there are no more lines. The function tests if it has reached the end of the file yet - returning true if it has and false if there is still more to be read. Once we know there is another line to be read in, reads in the line for us into a slot of...

» Access restriction on class due to restriction on required library

If you are using Eclipse or Rational Application Developer (RAD) and encounter the following error causing your build to break, here is a work around that will help you get past the problem:Error: "Access Restriction: The type {class name} is not accessible due to restriction on required library: {library path}"Work around: In Eclipse or RAD, go to Windows -> Preferences -> Java -> Compiler -> Errors/Warnings -> Deprecated and restricted API -> Forbidden reference (Access...

» How to Print in Python

Printing in Python is as simple as typing print followed by the string you wish to print.  You do not need to import any libraries.12>>> print "Hello World"Hello World You can also print the value of an integer or list simply by print 123456>>> x = [1, 2, 3]>>> print x[1, 2, 3]>>> y = 2>>> print y2If, however, you want to print a string AND some integer (or list), you need to cast to string.123>>> x = 42>>> print "The meaning...