PHP String Contains

Using PHP, we can easily find out if a bigger string contains another string without using complicated methods such as regular expressions. To do this, we make use of the PHP strpos function.

If the string we are looking for (the needle) is contained within the other string (the haystack), this function returns the (numeric) character location of the beginning of the string that we are searching for.

On the other hand, if the string we are looking for is not found, this function returns false. Therefore, by using a simple PHP if statement to check the result of the function we can determine if the string was found inside of the bigger string.

PHP strpos Syntax

The syntax for the strpos function is below:

$position = strpos($haystack, $needle);

Where $needle is the string that we are searching for, $haystack is the string that we are searching in, and $position is the position in the haystack where the first match is found.

PHP strpos Example - Finding if a string contains a particular term

Look at the code below:

<?php
 
// the haystack as it were
$string = "I love Tutorial Arena so much";
 
// the needle
$find = 'Arena';
 
// perform the search
$position = strpos($string, $find);
 
// We use ===  below because the needle we are looking for may
// start the haystack. In that case, the function would
// return 0 as the position of the first occurrence, but the if
// statement would treat that 0 as false if we used only ==
 
if ($position === false)
    echo "Not found";
else
    echo "Match found at location $position";
 
?>

If we were to run that we would get:

Match found at location 16

That means the term that we are looking for starts at the 16th character in the string. In other words, the letter 'A' from 'Arena' is at character location 16 in the haystack. Do remember that the first character in a string is always treated as character 0 as we see in our PHP substr tutorial.

PHP makes finding strings within strings pretty easy, but for more advanced string and pattern matching we may want to look into the use of regular expressions.

We hope you have learnt a lot in this PHP string contains tutorial. Happy string searching!

Citation: http://php.net/manual/en/function.strpos.php

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...