搜索文章以获取完全匹配关键字我找到的标准正则表达式不起作用

时间:2015-06-02 18:40:50

标签: php regex wordpress

我正在使用wordpress文章,搜索某些关键字,如“性别”,但不是“性”。

我试过

$string = "Testing by placing the word at the end sex. More words here.";

if ( preg_match("/\sex\b/i", strtolower($string) ) ) {}

$string = "Testing by placing the word at the end sex. More words here.";
if ( preg_match("~\sex\b~", strtolower($string) ) ) {}

但两者都返回false。

显然,在一篇文章中,这个词可以在开头,结尾,标点符号附近等等。我怎么能解释这个?

2 个答案:

答案 0 :(得分:3)

你只是错过了一个角色 - 在发生性行为后注意\b?这意味着它是一个单词边界。您需要在sex之前使用另一个,而不是\s - 这意味着空格。

$string = "Testing by placing the word at the end sex. More words here.";
if ( preg_match("~\bsex\b~", strtolower($string) ) ) {}
                   ^---- extra b here

答案 1 :(得分:0)

$re = "/sex\\b/m"; 
$str = "Testing by placing the word at the end sex. More words here."; 

preg_match_all($re, $str, $matches);