Search code examples
phpregexnewlinespace

Match numbers with space but not linebreak in between?


I devised the regular expression (see fiddle) /(\+|0|\()[\d()\s-]{6,20}\d/g to match phone numbers in the formats below.

(\+|0|\() is to match + or 0 or ( in the first place

[\d()\s-] is to match digits, brackets, spaces, hyphens in between

\d is to match a digit in the last place

+43 543 765 5434

0043 543 765 5434

0543 765 5434

+43 (0)543 765 5434

05437655434

0543-765-5434

Unfortunately this regex also matches numbers with linebreaks in between, like

"+43

654 416 4444" or

"stowasser09

65

808090"

  1. I therefore thought of replacing \s in the regex with [^\S\r\n] to match whitespaces but not linebreaks but couldn't get it to work?

  2. Also it would be nice to apply{6,20} to the whole regex, not just the [\d()\s-]-part please? I imagine something like /((\+|0|\()[\d()\s-]\d){6,20}/g, i.e. the whole matched phone number should not be shorter than 6 and not longer than 20 characters, including the + | 0 | ( in the first place and the last digit.

Thank you!


Solution

  • \s means: match any whitespace character. just replace it with a simple white space ' '

    /(\+|0|\()[\d() -]{6,20}\d/g
    

    see this demo