所以我試圖拆分包含電話號碼和擴展名的字符串,因爲有時字符串中存在擴展名。這是我的嘗試:使用preg_match將字符串拆分爲電話號碼和擴展名
$tests[] = "941-751-6550 ext 2204";
$tests[] = "(941) 751-6550 ext 2204";
$tests[] = "(941)751-6550 ext 2204";
$tests[] = "9417516550 ext 2204";
$tests[] = "941-751-6550 e 2204";
$tests[] = "941-751-6550 ext 2204 ";
$tests[] = "941-751-6550 extension 2204";
$tests[] = "941-751-6550 x2204";
$tests[] = "(941) 751-6550";
$tests[] = "(941)7516550";
$tests[] = "941-751-6550 ";
$tests[] = "941-751-6550";
foreach ($tests as $test) {
preg_match('#([\(\)\s0-9\-]+)(.+$)#',$test,$matches);
$phone = preg_replace('#[\-\(\)\s]#','',$matches[1]);
$extension = preg_replace('#[^0-9]#','',$matches[2]);
if ($phone == '9417516550'
&& ($extension == '2204'
|| $extension == '0')) {
echo "PASS: phone: $phone ext: $extension<br />";
} else {
echo "FAIL: phone: $phone ext: $extension<br />";
}
}
然而,當我運行這些測試,看它是否正確分割的電話號碼和擴展,我得到下面的輸出:
PASS: phone: 9417516550 ext: 2204
PASS: phone: 9417516550 ext: 2204
PASS: phone: 9417516550 ext: 2204
PASS: phone: 9417516550 ext: 2204
PASS: phone: 9417516550 ext: 2204
PASS: phone: 9417516550 ext: 2204
PASS: phone: 9417516550 ext: 2204
PASS: phone: 9417516550 ext: 2204
FAIL: phone: 941751655 ext: 0
FAIL: phone: 941751655 ext: 0
FAIL: phone: 9417516550 ext:
FAIL: phone: 941751655 ext: 0
正如你所看到的,當我完全排除一個擴展(最後四個測試)時,它會中斷。如何糾正preg_match()
正則表達式,使FAIL: ...
行看起來像PASS: phone: 9417516550 ext: 0
?
你絕對必須使用正則表達式? – GrumpyCrouton
我想你可以減少正則表達式,請檢查我的答案。 –