W3docs

PHP string "contains"

To check if a string contains another string in PHP, you can use the strpos() function.

To check if a string contains another string in PHP, you can use the strpos() function. This function returns the position of the first occurrence of a substring within a string, or FALSE if the substring is not found. (Note: In PHP 8.0+, the recommended approach is the built-in str_contains() function, which returns a boolean directly.)

Here's an example of how you can use strpos() to check if a string contains another string:

How to check if a string contains another string in PHP?

<?php

$string = 'The quick brown fox jumps over the lazy dog';
if (strpos($string, 'fox') !== false) {
    echo 'The string contains the word fox';
} else {
    echo 'The string does not contain the word fox';
}

This will output The string contains the word fox. If you want to check if the string contains a case-insensitive version of the substring, you can use the stripos() function instead of strpos():

<?php

$string = 'The quick brown fox jumps over the lazy dog';
if (stripos($string, 'FOX') !== false) {
    echo 'The string contains the word fox (case-insensitive)';
}

This will also output The string contains the word fox.

How to check if a string contains another string in PHP by using strstr() function?

<?php

$string = 'The quick brown fox jumps over the lazy dog';
if (strstr($string, 'fox')) {
    echo 'The string contains the word fox';
} else {
    echo 'The string does not contain the word fox';
}

This will also output The string contains the word fox. Note that strstr() is generally slower than strpos() because it returns the entire remaining string rather than just a position. For modern PHP (8.0+), str_contains($string, 'fox') is the recommended, most readable approach.