LeeTee LeeTee - 7 months ago 11
PHP Question

regular expression to make phone numbers bold - doesn't always work

I need to wrap bold tags around any phone number within a string. I have the following regex

/(\d[\d\s]*)(?=\s+)/


which works for this:


Call us on 0800 2458 452 now!


but not this:


Call us now on 0800 2458 452


So if the number occurs at the end of the string the regex does not work properly. It outputs the string as which misses the bold from the last three digits.

Call us now on <b>0800 2458</b> 452


Can anyone see what is wrong with the code?

$bold_text = preg_replace('/(\d[\d\s]*)(?=\s+)/', '<b>$1</b>', $text);

Answer

use word boundary instead of space

(\d[\d\s]*)(?=\b)

and better to add the same before

(?<=\b)(\d[\d\s]*)(?=\b)

to don't match B52

Comments