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

时间:2009-10-17 15:05:03

标签: 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");

我希望我的$ 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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

使用anonymous function和一些spl的另一个版本的php 5.3+:

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

答案 2 :(得分:1)

OOP很好。这是我的非OOP: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);

如果您愿意,可以将其分组到一个功能。

希望这有帮助。

答案 3 :(得分: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
)