PHP provides the strpos() function to check if a string contains a specific substring or not. The strpos() function returns the position of the first occurrence of a substring in a string. If substring not found, it will return false.

For example, let’s say you were checking the string “I love to program” to see if the word “program” was contained in the string.

$string = "I love to program!";
$substring = "program";

$result = strpos($string,$substring)   /* $result = 10 */

Finding if a String is in an Array Using the strpos() Function in PHP

Now, let’s say I wanted to loop over an array in PHP and see if a string is contained in that array.

I could write a function such as the one below, and use the strpos() to see if the string is in the array of strings.

function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (strpos($str,$a) !== false) return true;
    }
    return false;
}

$terms = ["frog", "dog", "elephant", "giraffe"];

$result = contains("frog",$terms) /* $result = true */
$result = contains("lamp",$terms) /* $results = false */

The Difference Between the strpos() and stripos() Functions in PHP

The strpos() function finds the position of a string and the stripos() function is the same as the strpos() function but is used for a case-insensitive search. Both return the position of the first occurrence of a string inside another string.

For example, you can see the difference in the following code of the results of using strpos() vs. stripos():

$string = "I love to program!";
$substring1 = "program";
$substring2 = "PROGRAM";

$result = strpos($string,$substring1)   /* $result = 10 */
$result = strpos($string,$substring2)   /* $result = false */
$result = stripos($string,$substring1)   /* $result = 10 */
$result = stripos($string,$substring2)   /* $result = 10 */

The str_contains() function in PHP 8

In PHP 8, the str_contains() function was introduced which returns true if the substring is in the string.

$string = "I love to program!";
$substring = "program";

$result = str_contains($string,$substring)   /* $result = true */

Using str_contains() can be useful if you don’t care about where the substring is in the string – only if it is contained in the string.

Categorized in:

Uncategorized,

Last Update: March 4, 2024