PHP Preg_match 匹配精确的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4305085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Preg_match match exact word
提问by ITg
I have stored as |1|7|11| I need to use preg_match to check |7| is there or |11| is there etc, How do I do this?
我已存储为 |1|7|11| 我需要使用 preg_match 来检查 |7| 有没有或|11| 有没有等,我该怎么做?
采纳答案by Xeoncross
Use the faster strposif you only need to check for the existence of two numbers.
如果您只需要检查两个数字是否存在,请使用更快的strpos。
if(strpos($mystring, '|7|') !== FALSE AND strpos($mystring, '|11|') !== FALSE)
{
// Found them
}
Or using slower regex to capture the number
或者使用较慢的正则表达式来捕获数字
preg_match('/\|(7|11)\|/', $mystring, $match);
Use regexpalto test regexes for free.
使用regexpal免费测试正则表达式。
回答by netcoder
Use \b
before and after the expression to match it as a whole word only:
\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
So in your example, it would be:
所以在你的例子中,它将是:
$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
回答by cambraca
If you really want to use preg_match
(even though I recommend strpos
, like on Xeoncross' answer), use this:
如果你真的想使用preg_match
(即使我推荐strpos
,就像 Xeoncross 的回答一样),使用这个:
if (preg_match('/\|(7|11)\|/', $string))
{
//found
}
回答by Yeroon
Assuming your string always starts and ends with an |
:
假设您的字符串始终以 开头和结尾|
:
strpos($string, '|'.$number.'|'));