What are some best practices for extracting integers from a string using regular expressions in PHP?

When extracting integers from a string using regular expressions in PHP, it is important to use the appropriate regex pattern to match only the desired integers. One common approach is to use the preg_match_all function with the pattern "/\d+/" to extract all integers from the string. Additionally, it's a good practice to check if any integers were found before using them in further processing.

$string = "There are 123 apples and 456 oranges in the basket.";
$integers = [];

if (preg_match_all('/\d+/', $string, $matches)) {
    $integers = $matches[0];
}

print_r($integers);