2011/05/18

Multiple Preg replace in PHP

You can do multiple preg replace with one function call, for example,

PHP, using GeSHi 1.0.8.8
  1. $subject = "{hello}";
  2. $patterns = array("/{/", "/}/");
  3. $replaces = array("{ldelim}", "{rdelim}");
  4. echo preg_replace($patterns, $replaces, $subject); 

Guess what your get? you get,

{ldelim{rdelim}hello{rdelim}

The reason you get this is that perg_replace executes multiple patterns one by one, so ‘{‘ is replaced by ‘{ldelim}’, and then ‘{ldelim}’ is replaced by ‘ {ldelim{rdelim}’.

I believe this is not what you wanted to get. You only want one ‘pattern’ is replaced once. So you can do this,

PHP (brief), using GeSHi 1.0.8.8
  1. $title = "{abdcd}";
  2. $patterns = array("/{/", "/}/");
  3. $replaces = array("LC", "RC");
  4. $title = preg_replace($patterns, $replaces, $title);
  5.  
  6. $patterns = array("/LC/", "/RC/");
  7. $replaces = array("{ldelim}", "{rdelim}");
  8. echo preg_replace($patterns, $replaces, $title);

Finally, you get,

{ldelim}hello{rdelim}

Note that in smarty template, to keep brace, you have to change ‘{ ‘or ‘} ‘to ‘{ldelim}’ or ‘{rdelim}’, or add {literal} and {/literal} around the code that you don’t want smarty engine to interpret it.

No comments:

Post a Comment