我有一个示例文本:
$text = "ác, def ác ghi ác xyz ác, jkl";
$search = "ác";
$_x_word = '/(\s)'.$search.'(\s)/i';
preg_match($_x_word, $text, $match_words);
echo count($match_words);
当我回显计数($match_words)时,结果返回为空
如何修复输出为2
首先,执行此操作时,请始终在 preg_quote
周围使用
$search
来转义正则表达式分隔符。
那么,你的代码就完全没问题了(即使没有
preg_quote
)。它为我输出 3。由于字符串中的非 ASCII 字符,您可能会遇到文件编码问题。您尝试过使用UTF8吗?
更改为:
$text = "ghi ác xyz ác, jkl";
$search = "ác";
$_x_word = '/\s(' . preg_quote($search) . ')\s/i';
preg_match_all($_x_word, $text, $match_words);
var_dump($match_words);
我所做的改变:
\s
周围的括号 - 你不需要匹配空格$search
的匹配组(括号内)preg_quote
var_dump
preg_match
为 preg_match_all
PS:可能用
\b
代替\s
会更好用
用途:
preg_match_all($_x_word, $text, $match_words, PREG_SET_ORDER);
而不是你的
preg_match
您必须使用
preg_match_all
和 /u
修改为 unicode 匹配才能结束,并更改括号以获得真正的匹配。
<?php
$text = "ác, def ác ghi ác xyz ác, jkl";
$search = "ác";
$_x_word = '/\s('.$search.')\s/ui';
preg_match_all($_x_word, $text, $match_words);
//full matches (with spaces)
var_dump($match_words[0]);
//only ác matches.
var_dump($match_words[1]);