用数组值替换定界符之间每次出现的文本(在 php 中)

replace each occurences of text between delimiter with array values (in php)

我想替换

之间的每一次出现
{{

}}

我想使用符号 {{ }} 内的 old_text 来选择新的, 我有这个数组:

$var["blue"]="ocean";
$var["red"]="fire";
$var["green"]="forest";

文本可以是:

people loves {{blue}} looks {{red}} and enjoy {{green}}

应该变成

people loves ocean looks fire and enjoy forest

我试过 preg_replace 但没有结果:

function replaceTags($startPoint, $endPoint, $newText, $source) { 
    $var["blue"]="ocean";
    $var["red"]="fire";
    $var["green"]="forest";

    return preg_replace('#('.preg_quote($startPoint).')(.*)('.preg_quote($endPoint).')#si', 'IDONT-KNOW-WHAT-PUT-HERE', $source);
}

尝试:

$string = 'people loves {{blue}} looks {{red}} and enjoy {{green}}';

foreach($var as $key => $val){
    str_replace('{{'.$key.'}}', $val, $string);
}

echo $string;

这是 PHP 函数的完美示例 preg_replace_callback():

$var = array(
    'blue'  => 'ocean',
    'red'   => 'fire',
    'green' => 'forest',
);
$template = 'people loves {{blue}} looks {{red}} and enjoy {{green}}';

$text = replaceTags('{{', '}}', $template, $var);


/**
 * Replaces the tags in a string using the provided replacement values.
 *
 * @param string $ldelim       the string used to mark the start of a tag (e.g. '{{') 
 * @param string $rdelim       the string used to mark the end of a tag (e.g. '}}') 
 * @param string $template     the string that contains the tags
 * @param array  $replacements the values to replace the tags
 */
function replaceTags($ldelim, $rdelim, $template, array $replacements)
{
    return preg_replace_callback(
        // The 'U' flag prevents the .* expression to be greedy
        // and match everything from the first to the last tag
        '#'.preg_quote($ldelim).'(.*)'.preg_quote($rdelim).'#U',
        function (array $matches) use ($replacements) {
            // $matches contains the text pieces that matches the capture groups
            // in the regexp
            // $matches[0] is the text that matches the entire regexp
            // $matches[1] is the first capture group: (.*)
            $key = $matches[1];
            if (array_key_exists($key, $replacements)) {
                // Replace the tag if a replacement value exists in the list
                return $replacements[$key];
            } else {
                // Don't replace the tag if a value is not assigned for it
                return $matches[0];

                // Alternatively, you can return a default placeholder string
                // or return '' to remove the tag completely
            }
        },
        $template
    );
}

我也会像 axiac 那样使用 preg_replace_callback,但是,这里有一个简单的方法来处理它。

<?php

// SET OUR DEFAULTS
$var["blue"]="ocean";
$var["red"]="fire";
$var["green"]="forest";

$string = 'people loves {{blue}} looks {{red}} and enjoy {{green}}';


// MAKE A CALLBACK FUNCTION THAT WILL REPLACE THE APPROPRIATE VALUES
$callback_function = function($m) use ($var) {
    return $var[$m[2]];
};


// RUN THE PREG_REPLACE_CALLBACK - CALLING THE FUNCTION
$string = preg_replace_callback('~(\{\{(.*?)\}\})~', $callback_function, $string);


// DYNAMITE
print $string;

use ($var) 附加到函数后,我们就可以……在我们的函数中使用 $var。所以我们需要做的就是使用它在大括号内匹配的部分作为数组的键。这让我们可以得到数组的值,其中键是 blue 和 return 来自我们函数的值。

当我们运行这个时,它输出如下:

people loves ocean looks fire and enjoy forest

这是一个工作演示:

http://ideone.com/2GzsoK