php正则表达式,用于提取电话号码


php regular expression for extracting a phone number

我需要php正则表达式方面的帮助。我有一个$text变量。例如:"foo-foo-random words呼叫者电话:+92243202229random words-foo-words"我想从$text中提取922432202229。请注意$text也可能包含其他类似的号码,所以我只想要紧跟在"呼叫者电话:"之后的号码以下是我尝试过的:

    $matches = array();
    preg_match_all("/Caller Phone : +[0-9]{12}$/", $text, $matches);
    $matches = $matches[0];

您需要使用()来收集Phone:后面的实际值,如下所示:

preg_match_all("/Caller Phone : ([0-9]+)$/", $text, $matches);

我还把{12}改成了+,所以只要继续,你也有所有的数字。然后必须进行验证。

只有使用(),才会将值返回到$matches变量中。

这应该更灵活、更安全:

$matches = array();
preg_match_all('/Caller Phone's*:'s*'(+|)([0-9]{8,12})/i', $text, $matches);
$phones = $matches[2];

您可以使用此代码

    $matches = array();
    preg_match_all("/Caller Phone:'+'d{12}/i", $text, $matches);
    $matches = $matches[0];

如果$text变量中有此数据

$text="foo foo随机单词来电电话:+9224320229随机单词foo words";

它将在您给定的数据上显示此结果

Array
(
    [0] => Array
    (
        [0] => Caller Phone:+922432202229
    )
)