php regex,从字符串中提取电话号码? [英] php regex, extract phone numbers from string?

查看:45
本文介绍了php regex,从字符串中提取电话号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的正则表达式有一个小问题,我用它来从强大的电话号码中提取电话号码

';打印_r($matches[0]);?>

输出

数组([0] =>718-838-3586[1] =>1052202932[2] =>800-308-4653[3] =>866-641-6949[4] =>800-871-0999)

这项工作很好,但它返回 1052202932 作为我不需要的结果之一.
实际上我不知道我的模式中缺失的部分在哪里.

解决方案

每个 [-] 之后的 ? 使 - 成为可选.如果你希望它是必需的,你可以删除 ? 这将使它成为必需的.另外,[-] 等价于 - 所以我去掉了不必要的字符类:

preg_match_all('/\b[0-9]{3}\s*-\s*[0-9]{3}\s*-\s*[0-9]{4}\b/',$output,$matches);

你也可以用 \d 替换所有的 [0-9] 以进一步缩短它:

preg_match_all('/\b\d{3}\s*-\s*\d{3}\s*-\s*\d{4}\b/',$output,$火柴);

i am having a small problem with my regex which i use to extract phone numbers from a strong

<?php
$output = "here 718-838-3586 there 1052202932 asdas dasdasd 800-308-4653 dasdasdasd 866-641-6949800-871-0999";
preg_match_all('/\b[0-9]{3}\s*[-]?\s*[0-9]{3}\s*[-]?\s*[0-9]{4}\b/',$output,$matches);
echo '<pre>';
print_r($matches[0]);
?>

output

Array
(
            [0] => 718-838-3586
            [1] => 1052202932
            [2] => 800-308-4653
            [3] => 866-641-6949
            [4] => 800-871-0999

)

this work fine but it returns 1052202932 as one of result which i don't need .
actually i don't know where is the missing part in my pattern .

解决方案

The ? after each [-] is making the - optional. If you want it to be required you can just remove the ? which will make it required. Also, [-] is equivalent to - so I got rid of the unnecessary character class:

preg_match_all('/\b[0-9]{3}\s*-\s*[0-9]{3}\s*-\s*[0-9]{4}\b/',$output,$matches);

You can also replace all of the [0-9] with \d to shorten it a bit further:

preg_match_all('/\b\d{3}\s*-\s*\d{3}\s*-\s*\d{4}\b/',$output,$matches);

这篇关于php regex,从字符串中提取电话号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆