用第二个数组中的值替换第一个数组中的字符串

k00*_*00k 3 php regex arrays

出于某种原因,我正在努力解决这个问题.

我有以下2个数组,我需要从$ img数组中获取数组值并将它们按顺序插入到$ text数组中,附加/替换%img_标记,如下所示:

$text = array(
    0 => "Bunch of text %img_ %img_: Some more text blabla %img_",
    1 => "More text %img_ blabla %img_"
);

$img = array("BLACK","GREEN","BLUE", "RED", "PINK");
Run Code Online (Sandbox Code Playgroud)

我希望我的$ text数组最终如此:

$text = array(
    0 => "Bunch of text %img_BLACK %img_GREEN: Some moretext blabla %img_BLUE",
    1 => "More text %img_RED blabla %img_PINK"
);
Run Code Online (Sandbox Code Playgroud)

注意:$ img数组中的项目数将有所不同,但始终与$ text数组中%img_的数量相同.

Pau*_*xon 5

这是你可以做到的一种方法,使用带有类的preg_replace_callback来包含跟踪要使用的$ img数组中的替换字符串的详细信息:

class Replacer
{
    public function __construct($img)
    {
       $this->img=$img;
    }

    private function callback($str)
    {
        //this function must return the replacement string
        //for each match - we simply cycle through the 
        //available elements of $this->img.

        return '%img_'.$this->img[$this->imgIndex++];
    }

    public function replace(&$array)
    {
        $this->imgIndex=0;

        foreach($array as $idx=>$str)
        {
            $array[$idx]=preg_replace_callback(
               '/%img_/', 
               array($this, 'callback'), 
               $str);
        }
    } 
}

//here's how you would use it with your given data
$r=new Replacer($img);
$r->replace($text);
Run Code Online (Sandbox Code Playgroud)