PHP Preg_match匹配确切的单词

时间:2010-11-29 15:18:48

标签: php regex preg-match

我存储为| 1 | 7 | 11 | 我需要使用preg_match来检查| 7 |在那里还是| 11 |是否有,我该怎么做?

4 个答案:

答案 0 :(得分:25)

在表达式之前和之后使用\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

答案 1 :(得分:2)

如果您只需要检查是否存在两个数字,请使用更快的strpos

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

或使用较慢的正则表达式来捕获数字

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

使用regexpal免费测试正则表达式。

答案 2 :(得分:0)

如果你真的想使用preg_match(即使我推荐strpos,就像Xeoncross的答案一样),请使用:

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

答案 3 :(得分:0)

假设您的字符串始终以|开头和结尾:

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