Skip to content
PHP Logo

What are the potential issues with using strpos() to find numbers within a string in PHP?

The potential issue with using strpos() to find numbers within a string in PHP is that it only returns the position of the first occurrence of a substring within a string. If the string contains multiple numbers, you may not be able to accurately locate all of them. To solve this issue, you can use a regular expression with the preg_match_all() function to find all numbers within the string.

php
$string = "There are 3 apples and 5 oranges in the basket.";
preg_match_all('/\d+/', $string, $matches);
$numbers = $matches[0];

foreach($numbers as $number) {
    echo $number . "\n";
}