- Instant help with your Php coding problems

Locate a substring within a string in PHP

Question:
How to locate a substring within a string in PHP?
Answer:
$text = 'The quick brown fox jumps over the lazy dog';

$foxPosition = strpos($text, 'fox');

echo 'The fox is at position ' . $foxPosition . '<br>';
Description:

If you want to know if a string contains a substring you can use the str_contains function. But if you also want to know exactly where the string in question is in the original text, you can use the strpos function. The strpos function finds the numeric position of the first occurrence of a substring within a string.

$text = 'PHP example text';

$position = strpos($text, 'PHP');

echo 'The PHP substring position is: ' . $position . '
';

Be careful when handling the return value, because if the string you are looking for is right at the beginning of the text, substr returns 0. However, if the string is not found, it returns false . For this reason, the following evaluation leads to an incorrect result:

# This is wrong!
if (!$position) {
    echo 'No substring found';
}

This code will say that it did not find the substring you are looking for, which is obviously wrong.

The correct check looks like this:

if ($position === false) {
    echo 'No substring found';
}

 

Share "How to locate a substring within a string in PHP?"
Interesting things
ChatGPT in a nutshell