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 ='https://ex.com/prom-nt/21538-asus-screen17.html'

using PHP preg_replace like

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

I get output

21538-asus

using PHP preg_replace like

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

I lose last digit (8) and get output

2153

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