3
我完全失去了这里的错误。任何帮助将不胜感激。使用preg_replace和FOR循环的PHP关键字替换
我正在为wordpress网站制作关键字替换工具。我的问题是,我的preg_replace似乎只在数组中的最后一个元素运行时通过发布内容。
下面的两个get_options仅仅是textarea字段,其中每个关键字和替换使用字符返回的单独行。
function keyword_replace($where) {
$keywords_to_replace = get_option('keywords_to_replace');
$keyword_links = get_option('keyword_links');
$KWs = explode("\n", $keywords_to_replace);
$URLs = explode("\n", $keyword_links);
$pattern = array();
$replacement = array();
for($i=0; $i< count($KWs); $i++) {
$pattern2 = '/<a[^>]*>(.*?)'.$KWs[$i].'(.*?)</a>/';
if(preg_match($pattern2, $where)) {
continue;
} else {
$pattern[$i] = '\'(?!((<.*?)|(<a.*?)))(\b'. $KWs[$i] . '\b)(?!(([^<>]*?)>)|([^>]*?</a>))\'si';
$replacement[$i] .= '<a href="'.$URLs[$i].'" target="_blank">'.$KWs[$i].'</a>';
}
}
return preg_replace($pattern, $replacement, $where, -1);
}
add_filter('the_content','keyword_replace');
var_dump()返回所有正确的信息,并且转储中没有任何内容被跳过。我试图弄清楚为什么它不能遍历整个数组。
感谢您的帮助, 拉斐尔
请问您可以添加一个'$ where'的样本列表吗?此外,使用'$ pattern [] = ...'而不是'$ pattern [$ i] = ...',因为您可能省略了指示符。 – Jan
嗨Jan, $只是自己调用。它使用wordpress调用the_content,因为它是一个过滤器。 我删除了$ i,没有区别。 – Rafael