views:

110

answers:

4

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;

etc..

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.

Thanks.

+1  A: 

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.

http://php.net/manual/en/function.str-replace.php

erjiang
+5  A: 

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
);
Jon Cram
+1  A: 

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%');
codez
This seems like a good way of doing it, and is closer to what I was looking for. I'll need to do some benchmarking to see how this compares to using the str_replace() function. I have a feeling str_replace() will be faster, but this class may be easier to use in practice.
Andy
A: 

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