【问题标题】:How to use preg_replace_callback如何使用 preg_replace_callback
【发布时间】: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 );

【问题讨论】:

    标签: preg-replace-callback


    【解决方案1】:

    更新

    使用preg_replace_callback的内置计数器变量:

    $new_text = preg_replace_callback("/$target_str/U", 
                    function($matches) use (&$count, $replacement_str)
                    {
                        $count++;
                        return ($count == 2) ? $replacement_str : $matches[0];
                    } , $article_text, -1, $count);
    

    【讨论】:

    • 它没有插入替换文本。我该如何调试它以找出什么不起作用?如果我只想要第二场比赛,为什么我需要增加?我添加了等于原始问题的变量,以防它有所作为。谢谢
    • @LTech 更新了答案。你需要有一个柜台,否则你无法弄清楚你在哪个州。
    • 我尝试复制并粘贴到您的代码中,但仍然没有任何反应。 “替换”是字符串还是变量?而“/t/U”也可以是变量吗?
    • 后来在我删除的代码中,if($num_matches>0) 的 b/c 不起作用。非常感谢它现在正在工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2013-03-17
    相关资源
    最近更新 更多