php preg_replace带空格的电话号码

[英]php preg_replace phone number with spaces


I have the following code that finds a number in a string and makes it bold. However, if there are spaces in the phone number the b tags get added multiple times. What do I need to amend to allow spaces to be anywhere within the phone number?

我有以下代码,在字符串中找到一个数字并使其变为粗体。但是,如果电话号码中有空格,则会多次添加b标签。我需要修改什么才能让空格在电话号码的任何地方?

$text = preg_replace('/(\d+)/', '<b>$1</b>', $text);

1 个解决方案

#1


1  

Use this Regex:

使用此正则表达式:

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

How it works:

怎么运行的:

(
  \d             # First digit
  [\d\s]*        # Any more digits or whitespace
)
(?=\s+)          # To make sure not to Capture last whitespace

It will not capture the last space, so rather than ending up with <b> 123 </b>, you will end up with <b>123</b>

它不会捕获最后一个空格,因此最终不会以 123 结束,最终会得到 123

Live Demo on Regex101

Regex101现场演示

Demo


This RegEx will also work:

此RegEx也将起作用:

/([\d\s]+)/

However, this will match the string if there are no digits, only spaces.

但是,如果没有数字,只有空格,这将匹配字符串。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2016/04/11/3a680ed2a6aed028ed8d1e58a920026e.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号