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

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

我有以下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");

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

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

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

解决方法:

这是你可以做到的一种方法,使用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);

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...