Search code examples
phpregexpreg-match

How to extract the last 2 delimitered numbers using regex


I have to extract the first instance of a number-number. For example I want to extract 8236497-234783 from the string bnjdfg/dfg.vom/fdgd3-8236497-234783/dfg8jfg.vofg. The string has no apparent structure besides the number followed by a dash and followed by a number which is the thing I want to extract.

The thing I want to extract may be at the very start of the string, or the middle, or the end, or maybe the entire string itself is just a number-number.

$b = "bnjdfg/dfg.vom/fdgd3-8236497-234783/dfg8jfg.vofg";

preg_match('\d-\d', $b, $matches);

echo($matches[0]);
// Expecting to print 8236497-234783

Solution

    1. You're missing the delimiter around the regexp. PHP's preg functions require that the regex begin with a punctuation character, and it looks for the matching character at the end of the regexp (because flags can be put after the second delimiter).
    2. \d just matches a single digit. If you want to match a string of digits, you should write \d+.
    3. You should require that the numbers be surrounded by word boundaries with \b, otherwise it will match the 3 at the end of fdgd3
    preg_match('/\b\d+-\d+\b/', $b, $matches);