Home > database >  PHP preg_replace to extract first number before dash
PHP preg_replace to extract first number before dash

Time:08-31

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,

CodePudding user response:

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

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

CodePudding user response:

If you place the [0-9] into the captured part, you might capture more than only digits before the last dash, see this regex example.

If you want a match for the first number before a dash, you can use preg_match:

Example

$input_line ='https://ex.com/prom-nt/21538-asus-screen17.html';
$pattern = "/^\S*?\K\d (?=-)/";

if (preg_match($pattern, $input_line, $match)) {
    echo $match[0];
}

The pattern matches:

  • ^ Start of string
  • \S*? Match optional non whitespace chars, as few as possible
  • \K Forget what is matched so far
  • \d Match 1 digits
  • (?=-) Assert - to the right

Output

21538
  • Related