Tutorial :How to replace multiple %tags% in a string with PHP


What is the best way of replacing a set of short tags in a PHP string, example:

$return = "Hello %name%, thank you for your interest in the %product_name%.  %representative_name% will contact you shortly!";  

Where I would define that %name% is a certain string, from an array or an object such as:

$object->name;  $object->product_name;  


I know I could run str_replace multiple times on a string, but I was wondering if there is a better way of doing that.



str_replace() seems an ideal option if you know the placeholders you intend to replace. This need be run just once not multiple times.

$input = "Hello %name%, thank you for your interest in the %product_name%.  %representative_name% will contact you shortly!";    $output = str_replace(      array('%name%', '%product_name%', '%representative_name%'),      array($name, $productName, $representativeName),      $input  );  


This class should do it:

<?php  class MyReplacer{    function __construct($arr=array()){      $this->arr=$arr;    }      private function replaceCallback($m){      return isset($this->arr[$m[1]])?$this->arr[$m[1]]:'';    }      function get($s){        return preg_replace_callback('/%(.*?)%/',array(&$this,'replaceCallback'),$s);    }    }      $rep= new MyReplacer(array(      "name"=>"john",      "age"=>"25"    ));  $rep->arr['more']='!!!!!';    echo $rep->get('Hello, %name%(%age%) %notset% %more%');  


The simplest and shortest option is preg_replace with the 'e' switch

$obj = (object) array(      'foo' => 'FOO',      'bar' => 'BAR',      'baz' => 'BAZ',  );    $str = "Hello %foo% and %bar% and %baz%";  echo preg_replace('~%(\w+)%~e', '$obj->$1', $str);  


From the PHP manual for str_replace:

If search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »