preg_replace

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
The Monkey
Forum Contributor
Posts: 168
Joined: Tue Mar 09, 2004 9:05 am
Location: Arkansas, USA

preg_replace

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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);
Post Reply