How can regular expressions be used in PHP to extract numbers from a string?

Regular expressions can be used in PHP to extract numbers from a string by using the preg_match_all function with the appropriate regex pattern. The regex pattern should match any sequence of digits in the string. By using preg_match_all, we can extract all occurrences of numbers in the string and store them in an array for further processing or manipulation.

$string = "I have 10 apples and 20 oranges";
preg_match_all('!\d+!', $string, $matches);
$numbers = $matches[0];

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