PHP Preg_match 精确匹配单词

标签 php regex preg-match

我已存储为 |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/

相关文章:

php - MySQL,如何为 SET 列选择所有可能的值

php - 为什么这个 PHP 正则表达式不匹配重音字符?

regex - 正则表达式是否可以设计为 'reverse' 以将其每个模式输出到列表或表格中?

正则表达式:指定 "space or start of string"和 "space or end of string"

php - 使用php获取字符串的一部分

php - 如何引发 PDOException?

php - SQL 查询返回错误的时间戳

php - 错误超时,使用codeigniter中的excel_reader上传excel文件

javascript - 为什么这个非捕获组会捕获?

c++ - 如何正确结束正则表达式 url 匹配