Locate a substring within a string in PHP
$text = 'The quick brown fox jumps over the lazy dog';
$foxPosition = strpos($text, 'fox');
echo 'The fox is at position ' . $foxPosition . '<br>';
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';
}
- Remove whitespace from the beginning and end of a string in PHP
- Locate a substring within a string in PHP
- Process CSV line in PHP
- Extract a substring from a string in PHP
- Split a string into words in PHP
- Replace spaces with dashes in PHP
- Replace only the first occurrence of a string in PHP
- Replace last occurrence of a string in a string in PHP
- Remove all attributes from HTML tags in PHP
- Remove HTML tags from a string except p, b, i and br in PHP
- Remove HTML tags from a string in PHP