我有一个示例文本:
$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
我有一个示例文本:
$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
Use:
preg_match_all($_x_word, $text, $match_words, PREG_SET_ORDER);
instead of your preg_match
您必须使用preg_match_allwith /umodified 来结束 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]);
这样的事情可能会做到这一点:
echo \preg_match_all('/\sác\s/i', "ác, def ác ghi ác xyz ác, jkl");
首先,当你这样做时,总是使用preg_quotearound$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_quotevar_dumppreg_match_preg_match_allPS:可能\b会\s更好地使用