PHP Preg_match匹配确切的单词

ITg*_*ITg 4 php regex preg-match

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

net*_*der 26

\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
Run Code Online (Sandbox Code Playgroud)

所以在你的例子中,它将是:

$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
Run Code Online (Sandbox Code Playgroud)


Xeo*_*oss 2

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

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

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

preg_match('/\|(7|11)\|/', $mystring, $match);
Run Code Online (Sandbox Code Playgroud)

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