捕获手机号码

时间:2012-02-20 22:53:18

标签: php regex

手机号码长度为11个字符,数字始终以07开头。

我想从字符串中捕获手机号码。下面的几个例子:

$String1 = "Text Text Text 07751 123 456 Text Text";
$String2 = "Text Text Text 07751 123456 Text Text"
$String3 = "Text Text Text 07751 123456. Text Text"
$String4 = "Text Text Text 07751123456, Text Text"

如何在PHP中完成?

5 个答案:

答案 0 :(得分:2)

您可以使用以下方式删除所有非数字字符:

function remove_non_numeric($string) {
   return preg_replace('/\D/', '', $string)
}

通过该检查,它以07等开始。

答案 1 :(得分:0)

试试这个:

$numbers = array();
preg_match_all('/[0-9\\- ]{6,}/', $string, $numbers);
print_r($numbers);

它应匹配由五个(您可以调整此数字)或更多0-9,短划线和空格字符组成的所有数字。

答案 2 :(得分:0)

/\b(?<myNumber>07[\d\s]+?)(?=[^\d\s])/

编辑:如果你可以说“数字中可能有空格,但最多只有2个”,你可以添加伪验证长度的范围(占尾随空格):

/\b(?<myNumber>07[\d\s]{9,12})(?=[^\d\s])/ 

“单词边界,后跟一系列以07(myNumber)开头的空格/数字,最多包含14个字符(11 + 3个空格),但在结尾处查看以查看非数字,非空格(数据中的字母或点),以便我们知道我们得到了整数“。 (然后从结果中删除空格)

答案 3 :(得分:0)

你可能正在寻找以07开头而且有9个数字+一些空格的正则表达式...你可以构建一个只能吃它找到的所有内容的正则表达式(包含空格和{{1 (十进制数字)。

\d

或者构建真正的正则表达式,它只匹配上面提到的格式:

~07[\d\s]+~

所有这些都是preg_match_all()

~07\d{3}\s*\d{3}\s*\d{3}~ 的参数

答案 4 :(得分:0)

我正在使用PCRE类型的RegExs。您希望捕获空格,句点和逗号可能出现的可能性。因此,您可以匹配它们,并且还可以创建空格和单词的边界。

\s(07(\d+\s*)*)(\.|,|\s(\w))

\s = <space>
() = match group, also used for the numbered replacement expression
\d = digit
\. = literal period
| = logical or. So A or B is (A|B)
\w = word character, any alpha character

我用\ s \ 1 \ s

的替换表达式对此进行了测试

结果

"Text Text Text 07751 123 456 ext Text"; <---replaced. See the missing "T"
"Text Text Text 07751 123 456 Text Text"; <--original

"Text Text Text 07751 123456 ext Text" <---replaced. See the missing "T"
"Text Text Text 07751 123456 Text Text" <--original

"Text Text Text 07751 123456  Text Text" <---replaced. See the missing "."
"Text Text Text 07751 123456. Text Text" <--original

"Text Text Text 07751123456  Text Text" <---replaced. See the missing ","
"Text Text Text 07751123456, Text Text" <--original

"Text Text Text 07751 123 456 ext Text"; <---replaced. See the missing "T"
"Text Text Text 07751 123 456 Text Text"; <--original