Home > Software design >  PHP - Regex for beginner
PHP - Regex for beginner

Time:07-23

My name is David from France and I need a Regex to comply with the following examples. I need to find datas between parentheses with 5 numbers, space and the name of the town, possibly followed by number of district. Here are some examples of what I need to find :

  • (05369 Toussus) OK
  • (56236 Ressons le long) OK
  • (56236 Ressons-le-long) OK
  • (44896 St-Erme-O.&R.) OK
  • (89569 amiens /1) OK
  • (89569 amiens /1/) OK
  • (56236 Ressons le long /2) OK

Here is what I don't want to comply with what I need :

  • (454683135 sdf1zg6er5e5z) KO
  • (gsdsgfdgsd 4561261) KO
  • (16 gsdvgfsvg jythjuyt) KO

I tried to use this regex but that doesn't work:

!\(([0-9]{5}.*[A-Z\-. \&\/].*[\/1-2]{2})\)!

I also tried this one but do not comply with all :

!\(([0-9]{5}.*[A-Z\-. \&\/])\)!

Can I get some help ?

Thank you in advance, David

CodePudding user response:

/\(\d{5}\s[a-zA-Z][\w\s\-\/\.&]*\)/

\( For (

\d{5} For 5 digits

\s For A single whitespace character

[a-zA-Z] For A single letter character

[a-zA-Z] For A single letter character

[\w\s\-\/\.&]* For any number (0-infinity) of letter characters, whitespace, -, /, ., &

\) For )

Test page and PHP usage:

$pattern = '/\(\d{5}\s[a-zA-Z][\w\s\-\/\.&]*\)/m';

preg_match_all($pattern, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

If you want to capture information with capture groups, this pattern will work with Postal Code as Group 1, Name of the Town as Group 2, and District number as an optional Group 3.

/\((\d{5})\s([a-zA-Z][\w\s\-\.&]*)(?>\s\/(\d)\/*)*\)/

CodePudding user response:

Thank you mcky ! It seems so easy when someone else write it ! lol That matches perfectly, thank you for your help ! :-D

  • Related