Check if String Contains Substring using str_contains in PHP 8.0

Check if String Contains Substring using str_contains in PHP 8.0

In versions prior to PHP 8.0, in order to check if a string contains a given substring, we can use the strpos function. This function returns the position of the first occurrence of a substring in a string. If the substring was not found, then the function returns false.

<?php

$text = 'Hello world';
if (strpos($text, 'world') !== false) {
    echo 'Found';
}

Often, the strpos function is used not properly. The following code snippet is not correct:

<?php

$text = 'Hello world';
if (strpos($text, 'Hello')) {
    echo 'Found';
}

In this case, the strpos function returns 0 because Hello is found at the beginning of the string. A condition evaluates to false, and the if block is not executed.

Since PHP 8.0, we can use the str_contains function to check if a string contains a substring. This function returns true if a substring was found, false otherwise.

<?php

$text = 'Hello world';
if (str_contains($text, 'Hello')) {
    echo 'Found';
}

Note that str_contains function is case-sensitive. In the following code, a substring was not found:

<?php

$text = 'Hello world';
if (str_contains($text, 'hello')) {
    echo 'Found';
} else {
    echo 'Was not found because the case does not match';
}

Leave a Comment

Cancel reply

Your email address will not be published.