Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract first integer in a string with PHP

Consider the following strings:

$strings = array(
    "8.-10. stage",
    "8. stage"
);

I would like to extract the first integer of each string, so it would return

8
8

I tried to filter out numbers with preg_replace but it returns all integers and I only want the first.

foreach($strings as $string)
{
    echo preg_replace("/[^0-9]/", '',$string);
}

Any suggestions?

like image 694
Fredrik Avatar asked Mar 01 '13 10:03

Fredrik


1 Answers

A convenient (although not record-breaking in performance) solution using regular expressions would be:

$string = "3rd time's a charm";

$filteredNumbers = array_filter(preg_split("/\D+/", $string));
$firstOccurence = reset($filteredNumbers);
echo $firstOccurence; // 3

Assuming that there is at least one number in the input, this is going to print the first one.

Non-digit characters will be completely ignored apart from the fact that they are considered to delimit numbers, which means that the first number can occur at any place inside the input (not necessarily at the beginning).

If you want to only consider a number that occurs at the beginning of the string, regex is not necessary:

echo substr($string, 0, strspn($string, "0123456789"));
like image 57
Jon Avatar answered Nov 15 '22 03:11

Jon