Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 对电话号码使用Preg_Match()进行调整_Php_Regex_Preg Match - Fatal编程技术网

Php 对电话号码使用Preg_Match()进行调整

Php 对电话号码使用Preg_Match()进行调整,php,regex,preg-match,Php,Regex,Preg Match,我正在使用preg_match从一段文字中提取美国电话号码的各个部分我已经可以提取号码。但是我想让匹配[0]只包括电话号码 问题:我的模式很接近,但我需要一些帮助来清除电话号码前的任何文本。如何摆脱前面的字符串“Hey my phone is” PHP代码 $pattern = '/.*?(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})' .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9

我正在使用
preg_match
从一段文字中提取美国电话号码的各个部分我已经可以提取号码。但是我想让
匹配[0]
只包括电话号码

问题:我的模式很接近,但我需要一些帮助来清除电话号码前的任何文本。如何摆脱前面的字符串“Hey my phone is”

PHP代码

$pattern = '/.*?(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})'
    .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})'
    .'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?.*?/';;

$subject = 'Hey my phone is 911-628-4539, call me tonight at 9:16:00pm, my room is 122-1001';

preg_match($pattern, $subject, $match);

print_r($match);

只需删除:
*?


从你的正则表达式。如果您不需要它,为什么要匹配它?

您捕获文本部分,因为您匹配了它。是领先的
*?
做到了这一点


要么删除它,要么在它后面添加
\K

为了可读性,您应该使用
/x
。使用
\s
查找实际需要空间的少数位置。此外,
*?
是多余的,如果需要,可以减少为
*
@Nyxynyx您还应该将其从模式的末尾删除。
Array ( [0] => Hey my phone is 911-628-4539 [1] => 911 [2] => 628 [3] => 4539 )