Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace strings in first array with values from second array

Tags:

arrays

regex

php

For some reason I'm struggling with this.

I have the following 2 arrays and I need to take the array values from the $img array and insert them in order into the $text array, appending/replacing the %img_ tags, like so:

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

I want my $text array to end up like so:

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

NOTE: The number of items in the $img array will vary but will always be the same as the number of %img_ in the $text array.

like image 608
k00k Avatar asked Dec 17 '25 00:12

k00k


2 Answers

Here's one way you could do it, using preg_replace_callback with a class to wrap up the details of tracking which replacement string in your $img array to use:

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);
like image 183
Paul Dixon Avatar answered Dec 19 '25 12:12

Paul Dixon


Another version for php 5.3+ using an anonymous function and some 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);
like image 30
VolkerK Avatar answered Dec 19 '25 14:12

VolkerK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!