出于某种原因,我正在努力解决这个问题.
我有以下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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。