LeeTee LeeTee - 2 years ago 62
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


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 Source

use word boundary instead of space


and better to add the same before


to don't match B52

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download