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
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.
Thanks for your help.
CodePudding user response:
You can use
[ (]?\d(?:[-() \s.]*\d){8,14}(?![-() \s.]*\d)
Details:
[ (]?
- an optional(
\d
- a digit(?:[-() \s.]*\d){8,14}
- eight to 14 occurrences of a-
,(
,)
,.
char and then a digit(?![-() \s.]*\d)
- not immediately followed with a-
,(
,)
,.
char and then a digit.
See the regex demo.