2013-03-13 127 views
0

我有一個PHP代碼來檢查字符串內收集的字符串,我的代碼是這樣的:使用正則表達式來檢查特定的字符串

$string = '01122028K,02122028K,03122028M-1'; 
$search = '03122029M' 
echo preg_match('/\b' . $search . '\b/', $string); 

它返回TRUE ...

我該怎麼辦與我的正則表達式返回它假,我希望它只返回TRUE當變量$ search中的字符串實際上匹配變量$字符串, 因此$ search =「03122029M」將返回FALSE $ search =「03122029M-1」會返回TRUE

謝謝你

+0

這裏看看http://stackoverflow.com/questions/5752829/regular-expression-for-exact-match-of-a-word – BenB 2013-03-13 17:20:30

回答

0

問題是你正在使用的邊界標尺:\b包括-

您可以使用字符類來分隔空格和逗號。還包括行的開始,並在檢測線在行尾搭上情況:

preg_match('/(^|[\s,])' . $search . '([\s,]|$)/', $string); 
0

我不認爲你真的需要這裏正則表達式。此外,你也會開放自己的一個逃避噩夢。

如果添加逗號的開始和$string結束時,你可以通過逗號包裹它,以及匹配整個$search作爲一個單一的實體:

echo (strpos(',' . $string . ',', ',' . $search . ',') !== FALSE) 
0

\ 1b包括 - 在你」重新匹配。取而代之的是使用逗號來匹配 - 你可以通過在字符串的開始和結尾加一個逗號來實現。

$string = '01122028K,02122028K,03122028M-1'; 
$string = ','.$string.',' 
$search = '03122029M' 
echo preg_match('/,' . $search . ',/', $string); 
1

請勿使用正則表達式。

echo in_array($search, explode(',', $string)); 
+0

謝謝Barmar,我認爲這是良好和快速的解決方案我的問題。它的工作.. :-) – 2013-03-14 00:25:38

相關問題