Page 1 of 1

preg_replace

Posted: Thu Oct 21, 2004 7:15 pm
by The Monkey
Quick question with preg_replace:

Code: Select all

<?php
$template = preg_replace('#\{(.*)\}#', '', $template);
?>
This function is intended to "delete" any unused template variables, such as {unused}. However, if the template variable is inside quotes, such as

Code: Select all

&lt;a href="&#123;unused&#125;"&gt;Blah&lt;/a&gt;
It removes {unused}, all right, and takes the quote right after it with it!!!

It only does this with double quotes, however. What did I do wrong?

- Monkey

Posted: Thu Oct 21, 2004 7:34 pm
by feyd
not sure (as I can't test any code on this machine), but try this instead:

Code: Select all

&lt;?php

$template = preg_replace('#\{.*?\}#','',$template);
?&gt;
just be careful with these since they are dumb.

I'd use a better template replacement routine like:

Code: Select all

&lt;?php

$template_vars = array('whatever'=&gt;'something','foo'=&gt;'bar');

function substControl($match,$vars)
{
  $ret = '';
  if(isset($vars&#1111;$match])) $ret = $vars&#1111;$match];
  return $ret;
}

$template = preg_replace('#\{(&#1111;a-zA-Z\\.]&#1111;a-zA-Z_\\.]*)\}#e', 'substControl(''\\\\1'', \$template_vars)', $template);