我正在使用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。
显然,在一篇文章中,这个词可以在开头,结尾,标点符号附近等等。我怎么能解释这个?
答案 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);