开发者

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:

$obj开发者_Python百科ect->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.


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.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜