我已存储为 |1|7|11| 我需要使用 preg_match 来检查 |7|有没有|11|有没有等等,我该怎么做?
最佳答案
在表达式前后使用 \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
关于PHP Preg_match 精确匹配单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4305085/