views:

121

answers:

3

I'm creating a very simple PHP templating system for a custom CMS/news system. Each article has the intro and the full content (if applicable). I want to have a conditional of the form:

{continue}click to continue{/continue}

So if it's possible to continue, the text "click to continue" will display, otherwise, don't display this whole string. So far, it works like this: if we can continue, remove the {continue} tags; otherwise, remove the whole thing.

I'm currently using preg_match_all to match the string in the second case. What is the best function for removing the matched text? A simple str_replace, or something else?

Or is there a better way to implement this overall?

+4  A: 

Why not use preg_replace_callback?

Specifically:

preg_replace_callback('!\{continue\}(.*)\{/continue\}!Us', 'replace_continue', $html);

function replace_continue($matches) {
  if (/* can continue */) {
    return $matches[1];
  } else {
    return '';
  }
}

I find preg_replace_callback to be incredibly useful.

cletus
Interesting solution, that looks pretty good.
DisgruntledGoat
+2  A: 

Sorry I know people have been ridiculing this kind of answer, but just use Smarty. Its simple, stable, clever, free, small and cheap. Spend an hour learning how to use it and you will never look back.

Go to www.smarty.net

Toby Allen
I agree he should just use real templating engine, but not smarty: http://www.nosmarty.net/
porneL
WOW a whole website dedicated to a long winded rant about why some bloke doesn't like smarty. :)
Toby Allen
The author of that page may be correct, but I wasn't impressed with any of their points. The alternatives aren't in fact alternatives either, Symfony uses tons of inline php the last time I checked, and only PHPTAL was an actual template language. I also haven't experienced the bugginess either.
Dana the Sane
Perhaps I should have been more clear in my question, but I am not creating a fully-fledged templating system to allow users to create/output whatever variables they like. There are only a few, fixed variables like {headline}, {content} and so on.
DisgruntledGoat
Once you allow conditionals I would use smarty.
Toby Allen
+1  A: 

For PHP templating systems the proper way is to parse the template (using state machine or at least preg_split), generate PHP code from it, and then use that PHP code only. Then you'll be able to use normal if for conditional expressions.

Regular expressions aren't good idea for implementing templates. It will be PITA to handle nesting and enforce proper syntax beyond basic cases. Performance will be very poor (you have to be careful not to create backtracking expression and even then you'll end up scanning and copyng KBs of templates serveral times).

porneL
Thanks for the advice but this really is a very simple system, with no more than 8 fixed constants that I decide. There will be no scope for complex conditionals, only this single "display if it makes sense to".
DisgruntledGoat