Reputation: 33
I'm using a simple regex in PHP to parse a custom template
$row = preg_replace_callback(
'/\^([^\^]+)\^/', create_function ('$m', 'global $fields_ar; return $fields_ar{$m[1]};'),
$template
);
Basically everything between two ^ is substituted with the corresponding variable name value e.g. if $template is:
<td>^title_source^ by ^author_source^<br/>
and
$fields_ar['title_source'] == 'my title' and $fields_ar['author_source'] == 'my author'
$row becomes:
<td>my title by my author<br/>
Everythings works fine but I want to change the delimiter; instead of ^, which has the risk to be contained between other two ^, I want to use a string e.g. "sel3ction", however:
$row = preg_replace_callback(
'/sel3ction([^sel3ction]+)sel3ction/', create_function ('$m', 'global $fields_ar; return $fields_ar{$m[1]};'),
$template
);
doesn't work; I'm pretty sure the problem is in the negative part.
Any suggestions?
I know it is not a "clean" approach, cause even the strangest string can be tricky but for the moment I want to try using this method. If you have a more standard solution, of course is welcome.
Thanks!
Upvotes: 3
Views: 418
Reputation:
You can tell your expression not to be greedy when matching .
using the lazy quantifier (?
):
/sel3ction(.+?)sel3ction/
This tells the regular expression engine not to match what comes after the .
(in this case, "sel3ction") with whatever else might be matched.
Upvotes: 1