2010-11-29 148 views

回答

2

如果您只需檢查兩個數字是否存在,請使用更快的strpos

if(strpos($mystring, '|7|') !== FALSE AND strpos($mystring, '|11|') !== FALSE) 
{ 
    // Found them 
} 

或者使用正則表達式慢捕捉到數

preg_match('/\|(7|11)\|/', $mystring, $match); 

使用regexpal測試正則表達式是免費的。

+0

這也將像17,27,71和111,211和114號僅舉幾例 – Yeroon 2010-11-29 15:22:16

+0

謝謝返回TRUE,這是一個更簡單的方法和工作! – ITg 2010-11-29 15:22:51

0

如果你真的想使用preg_match(儘管我建議strpos,就像Xeoncross的回答),使用此:

if (preg_match('/\|(7|11)\|/', $string)) 
{ 
    //found 
} 
0

假設你的字符串總是啓動並與|結束:

strpos($string, '|'.$number.'|')); 
17

使用\b表達式前後僅匹配它作爲一個整詞:

$str1 = 'foo bar';  // has matches (foo, bar) 
$str2 = 'barman foobar'; // no matches 

$test1 = preg_match('/\b(foo|bar)\b/', $str1); 
$test2 = preg_match('/\b(foo|bar)\b/', $str2); 

var_dump($test1); // 1 
var_dump($test2); // 0 

所以,在你的榜樣,那就是:

$str1 = '|1|77|111|'; // has matches (1) 
$str2 = '|01|77|111|'; // no matches 

$test1 = preg_match('/\b(1|7|11)\b/', $str1); 
$test2 = preg_match('/\b(1|7|11)\b/', $str2); 

var_dump($test1); // 1 
var_dump($test2); // 0