PHP preg_replace to extract first number before dash

Many examples are – but still a stumbling block in my mind.

I need to extract first number 21538 from links like

$input_line =''

using PHP preg_replace like

preg_replace('/(^\D+)(.*)-(.*)/', '\2', $input_line);

I get output


using PHP preg_replace like

preg_replace('/(^\D+)(.*)[0-9]-(.*)/', '\2', $input_line);)

I lose last digit (8) and get output


not 21538 – so a solution is somewhere near but can’t catch it.

Thx in advance for any hint to try,

>Solution :

you should move [0-9] into to the capture part. I mean this:

preg_replace('/(^\D+)(.*[0-9])-(.*)/', '\2', $input_line);

Leave a Reply