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

3

由于某些原因,我在这方面遇到了困难。

我有以下两个数组,需要将$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数组最终看起来像这样:

$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_数量相同。

4个回答

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);

很高兴在这里看到一些面向对象的解决方案 :) - Mark
啊,谢谢Paul。做得非常好!省去了我很多烦恼。 - k00k

2
另一种适用于 PHP 5.3+ 的版本,使用 匿名函数 和一些 spl
$text = array(
  "Bunch of text %img_ %img_: Some more text blabla %img_",
  "More text %img_ blabla %img_"
);
$img = new ArrayIterator(array("BLACK","GREEN","BLUE", "RED", "PINK"));
foreach($text as &$t) {
  $t = preg_replace_callback('/%img_/', function($s) use($img) {
      $rv = '%img_' . $img->current();
      $img->next();
      return $rv;
    }, $t);
}

var_dump($text);

这与我最初解决问题的方式类似。感谢VolkerK。 - k00k

1

面向对象编程很好。这是我的非面向对象编程版本 :D

$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");

$newtext = array();
$k = 0;
$count = count($text);
for($i = 0; $i < $count; $i++) {
    $texts = split("%img_", $text[$i]);
    $jtext = $texts[0];
    $subcount = count($texts);
    for($j = 1; $j < $subcount; $j++) {
        $jtext .= "%img_";
        $jtext .= $img[$k++];
        $jtext .= $texts[$j];
    }
    $newtext[] = "$jtext\n";
}

print_r($newtext);

如果您喜欢,可以将其分组为一个函数。

希望这可以帮到您。


1

这里是另一种方法:

<?php

$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");

foreach ($text as &$row) {
        $row = str_replace("%img_", "%%img_%s", $row);
        $row = vsprintf($row, $img);
}

print_r($text);

输出结果为:

Array
(
    [0] => Bunch of text %img_BLACK %img_GREEN: Some more text blabla %img_BLUE
    [1] => More text %img_BLACK blabla %img_GREEN
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接