Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading