interesting problem with 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
will
Forum Contributor
Posts: 120
Joined: Fri Jun 21, 2002 9:38 am
Location: Memphis, TN

interesting problem with preg_replace()

Post by will »

so i'm using preg_replace() to parse a template for XML data. my template is a simple string along the lines of...

Code: Select all

$html_tpl = '
<b>%title%</b><br>
<i>%time%</i><br>
<a href="%url%">%url%</a><br>
<br>';
where the XML tag names are between the %s. my preg_replace call is...

Code: Select all

$html = preg_replace('/\%(.+)\%/ie', "$\\1", $html_tpl);
The problem is that it is seeing

Code: Select all

%">%
(from the url line of the template) and trying to replace that. is there any way to have each percent sign be matched only once?
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post by gnu2php »

Does this work any better?

Code: Select all

$html = preg_replace('/\%(&#1111;^\%]+)\%/ie', "$\\1", $html_tpl);
will
Forum Contributor
Posts: 120
Joined: Fri Jun 21, 2002 9:38 am
Location: Memphis, TN

Post by will »

surprisingly, yes it does... although i can't honestly say i understand why :-\

thanks.
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post by gnu2php »

Actually, I don't understand either. I just know that it's usually better to do x[^x]+x than x.+x
Post Reply