【发布时间】:2014-06-12 07:36:13
【问题描述】:
我正在尝试替换第二次出现的 $target_str。
如果有人能解释 preg_replace_callback 的工作原理,我将不胜感激。 我不明白 function($match) 部分。如何设置它以使其匹配第二次出现并仅替换该字符串?
我有代码(但它不能按我的意愿工作)。
$replacement_params['target_str'] = "[\n]";
$replacement_params['replacement_str'] = "\n<ads media=googleAds1 />\n";
$target_str = $this->params['target_str'];
$replacement_str = $this->params['replacement_str'];
$num_matches;
$i = 0;
$new_text = preg_replace_callback("/".$target_str."/U",
function ( $match ) {
if ( $i === 1 ) {
return $replacement_str;
} else {
return $match[0];
}
$i++;
} , $article_text, 1, $num_matches );
【问题讨论】: