简体   繁体   English

PHP中的正则表达式,使用一个Regex提取电话/手机号码的所有可能组合

[英]Regular Expression in PHP to extract all possible combination of phone/mobile numbers using one Regex

i am using php and wants to extract phone/mobile numbers from string, i have string with multiple format of phone numbers like 我正在使用php并想从字符串中提取电话/手机号码,我的字符串具有多种格式的电话号码,例如

$str = '(123) 456-7890 or (123)456-7890 and 1234567890 test "123.456.7890" another test "123 456 7890"';

i had write one RE as, 我写了一个RE

$phoneMatches = '';
$str = '(123) 456-7890 or (123)456-7890 or 1234567890 or "123.456.7890" or "123 456 7890"';
$phonePattern = '/\b[0-9]{3}\s*[-]?\s*[0-9]{3}\s*[-]?\s*[0-9]{4}\b/';
preg_match_all($phonePattern, $str, $phoneMatches);
echo "<pre>";
print_r($phoneMatches);
exit;

but it gives me output like this, 但这给了我这样的输出,

Array
(
    [0] => Array
        (
            [0] => 1234567890
            [1] => 123 456 7890
        )
)

Means only two, but i want all the possible combination of phone numbers and mobile numbers from string of text by using only ONE Regular expression. 仅意味着两个,但是我只希望使用一个正则表达式就可以从文本字符串中获得电话号码和手机号码的所有可能组合。

Thanks 谢谢

I know I'm late, and I'm not sure if this is what you wanted, but I came up with this solution: 我知道我来晚了,并且不确定这是否是您想要的,但是我想出了以下解决方案:

[+()\d].*?\d{4}(?!\d)

Demonstration: regex101.com 演示: regex101.com

Explanation: 说明:

  • [+()\\d] - We start by matching anything that might represent the start of a phone number. [+()\\d] -我们首先匹配任何可能代表电话号码开头的内容。
  • .*?\\d{4} - Then we match anything (using a lazy quantifier) until we reach four ending digits. .*?\\d{4} -然后我们匹配所有内容(使用惰性量词),直到达到四个结尾数字。 Just a little note: I considered this as a rule, but it might not always apply. 请注意:我认为这是一个规则,但可能并不总是适用。 You'd then need to modify the regex to include other cases. 然后,您需要修改正则表达式以包括其他情况。
  • (?!\\d) - This is a negative lookahead and it means that we don't want any matches followed by a digit character. (?!\\d) -这是一个否定的超前查询,表示我们不希望任何匹配后跟数字字符。 I used this to avoid some half-matches. 我用它来避免半场比赛。

Another observation is that this regex doesn't validate any phone number. 另一个观察结果是该正则表达式不会验证任何电话号码。 You could have anything in between the matches, mainly because of this part: .*?\\d{4} . 比赛之间您可能会有任何事情,主要是因为这部分: .*?\\d{4} This will work depending on what kind of situation you intend to use it. 这将取决于您打算使用哪种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM