如何使用preg_match获得差异

时间:2014-03-10 12:48:37

标签: php regex preg-replace preg-match

<?php
$format='(212) ### ### ##';
$phone='(212) 121 333 45';
$format=str_replace('(','\(',$format);
$format=str_replace(')','\)',$format);
$format=str_replace('.','\.',$format);
$format=str_replace('#','[0-9]',$format);
$pattern="/^".$format."$/";
//pattern->  /^\(212\) [0-9][0-9][0-9] [0-9][0-9][0-9] [0-9][0-9]$/
if (preg_match($pattern,$phone)) echo 'true'; else echo 'false';
?>

输入(212)121 333 45 我希望结果为; 1213345

这是成功但这只是检查。我想要同时匹配的字符。

1 个答案:

答案 0 :(得分:1)

你可以通过一点“正则表达式构建”工作来做到这一点:

$format='(212) ### ### ##';
$phone='(212) 121 333 45';

// Quote any characters such as ( in the format so they match the input literally
// $regex == \(212\) ### ### ##
$regex = preg_quote($format, '/');

// Then surround any groups of #s with parens, making them capturing groups
// $regex == \(212\) (###) (###) (##)
$regex = preg_replace('/#+/', '(\0)', $regex);

// Finally, replace the placeholder # with \d and surround with slashes
// $regex == /\(212\) (\d\d\d) (\d\d\d) (\d\d)/
$regex = '/'.str_replace('#', '\d', $regex).'/';

现在我们准备好了:

if (preg_match($regex, $phone, $matches)) {
    echo "Matched: ".implode('', array_slice($matches, 1));
}
else {
    echo "No match";
}

构造array_slice($matches, 1)创建每个捕获组内容的数组,因此使用示例输入将生成数组['121', '333', '45']implode将这些位加在一起,生成12133345

<强> See it in action