Regex in php- catching 9 types of numbers out of a string

Viewed 56

I just started coding and have a little problem with regex in PHP.

I am trying to catch the following number types out of a string.

000 000 00 00 -
000 000 00 0 -
000 000 00 -
000.000.00.00 -
000.000.00.0 -
000.000.00 -
0000000000 -
000000000 -
00000000 -

And of course the 0 stands for a number between 0-9.

This is the pattern I've tried:

$pattern = "/\d{3}[. ]\d{3}[. ]\d{2}[. ]?\d{1-2}?/";

Something is wrong here, but I don't understand what?

Can you help me?

1 Answers

It seems you may use

/\b\d{3}([.\s]?)\d{3}\1\d{2}(?:\1\d{1,2})?\b/

See the regex demo

Details

  • \b - a word boundary (if the numbers can be glued to letters or _ remove this or replace with (?<!\d))
  • \d{3} - 3 digits
  • ([.\s]?) - an optional . or whitespace, 1 or 0 times, captured into Group 1
  • \d{3} - 3 digits
  • \1 - same value as in Group 1
  • \d{2} - 2 digits
  • (?:\1\d{1,2})? - an optional sequence of
    • \1 - same value as in Group 1
    • \d{1,2} - 1 or 2 digits
  • \b - a trailing word boundary (remove/replace (?!\d) depending on the actual requirements).

In PHP:

$contents = file_get_contents('test.txt');
$pattern = '/\b\d{3}([.\s]?)\d{3}\1\d{2}(?:\1\d{1,2})?\b/';
preg_match_all($pattern, $contents, $results);
print_r($results);

Mind the single quotes around the pattern: if you use double quotes instead, you will have to double the backslashes (at least with \1) because "\1" defines a char with an octal number 1 while '\1' will be parsed as a backslash and 1.

Related