Home > other >  Regex to match phone numbers, but in text paragraph
Regex to match phone numbers, but in text paragraph

Time:03-24

I would like to highlight phone numbers in a text with the PHP function preg_replace().

This works pretty well:

(?=(?:\D*\d\D*){8,14}$)[- \d() ]*

It almost matches those different formats:

01 02 03 04 05
0102030405
 33102030405 01-02-03-04-05
01.02.03.04.05
 33 1 02 03 04 053
(33)102030405

DEMO

But now I would like to make it running with this test text:

blabla 01 02 03 04 05 blabla 0102030405 blabla 33102030405 blabla 01-02-03-04-05 blabla 01.02.03.04.05 blabla 33 1 02 03 04 05 blabla (33)102030405

I do not speak fluently regex, I've tried many things but failed.

DEMO

Thanks for your help.

CodePudding user response:

You can use

[ (]?\d(?:[-() \s.]*\d){8,14}(?![-() \s.]*\d)

Details:

  • [ (]? - an optional or (
  • \d - a digit
  • (?:[-() \s.]*\d){8,14} - eight to 14 occurrences of a -, (, ), , whitespace or . char and then a digit
  • (?![-() \s.]*\d) - not immediately followed with a -, (, ), , whitespace or . char and then a digit.

See the regex demo.

  • Related