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