Peter Bennett Peter Bennett - 2 months ago 8x
PHP Question

Extract first number(s) from variable

I have variables that always start with a number or numbers and need the script to determine where this number ends, now for an example the variable can be like the following:


1 hello1.gif


123456 hello1.gif

What I am trying to say is an explode function would not work, and my regex is very poor, I just need to be left with the first number and ignore any other number in the string. I just need to be left with the number(s) in bold.

Thanks in advance...

$arr = str_split($str);
for($i = 0; $i < count($arr); ++$i){
       echo "Number ends at index: " . $i;

You could also put the numbers into an array using $arr[$i] if you so wish. This is probably a lot more readable than using regex.

You could add logic to allow one decimal point but from the question it seems you only want integers. - Example of working code