PHP Preg_匹配精确单词
我已存储为| 1 | 7 | 11| 我需要使用preg|u match来检查| 7 |是否存在或| 11 |是否存在等,我如何做到这一点?如果只需要检查是否存在两个数字,请使用更快的速度PHP Preg_匹配精确单词,php,regex,preg-match,Php,Regex,Preg Match,我已存储为| 1 | 7 | 11| 我需要使用preg|u match来检查| 7 |是否存在或| 11 |是否存在等,我如何做到这一点?如果只需要检查是否存在两个数字,请使用更快的速度 if(strpos($mystring, '|7|') !== FALSE AND strpos($mystring, '|11|') !== FALSE) { // Found them } 或者使用较慢的正则表达式捕获数字 preg_match('/\|(7|11)\|/', $mystring
if(strpos($mystring, '|7|') !== FALSE AND strpos($mystring, '|11|') !== FALSE)
{
// Found them
}
或者使用较慢的正则表达式捕获数字
preg_match('/\|(7|11)\|/', $mystring, $match);
用于免费测试正则表达式。如果您确实想使用
preg\u match
(尽管我建议使用strpos
,就像Xeoncross的回答一样),请使用以下方法:
if (preg_match('/\|(7|11)\|/', $string))
{
//found
}
假设字符串始终以
|
开头和结尾:
strpos($string, '|'.$number.'|'));
在表达式前后使用
\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
为了清楚起见,您可以将
(7 | 11)
替换为(7 | 11 | 13)
,例如,匹配7、11或13。