我有一个示例文本:的preg_match在PHP不工作时,计数结果返回
$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_match在PHP不工作时,计数结果返回
$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匹配才能结束,并更改paranthesis以获得真正的匹配。
<?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]);
http://ideone.com/KbkII ---你确定你试过运行它吗? – zerkms
ps:使用'var_dump($ match_words);' – zerkms
@zerkms:var_dump($ match_words)=>空 –