cancel
Showing results for 
Search instead for 
Did you mean: 

PHP: Template script problem with preg_replace

7up
Community Veteran
Posts: 15,828
Thanks: 1,583
Fixes: 17
Registered: ‎01-08-2007

PHP: Template script problem with preg_replace

Hi
I have written my own function to parse my template and replace tokens with their appropriate value.
Here is an example:

<html>
<__Some Content__> <__More Content__> <__Something Else__>
</html>

Now in my function I am using str_replace() to replace the tokens with their appropriate value - if it exists. This is how I pass do it in php:

$Values['__Some Content__'] = 'Some';
$Values['__More Content__'] = 'More';
$Values['__Something Else__'] = 'Here';

Normally this isn't a problem. If however I only replace the middle token I do have a problem:

$Values['__More Content__'] = 'More';

At the end of the function I use preg_replace to blank out the unused tokens - for security (basically I hide any clue that admin links may be there).
This is what I'm using:

$Template = preg_replace('/\<__(.*)__\>/', '', $Template);

Doing this causes a problem - It looks at the entire line, recognises the beginnning and end on both the first and last key and blanks out the entire lot!
Just to recap:

//It see's the first <__(and last)__> and treats it as one token and blanks out the entire thing
// including my content in the middle:
<__(Some Content__> More <__Something Else])__>

Any ideas how I can deal with this?
I need a new signature... i'm bored of the old one!
2 REPLIES 2
spraxyt
Resting Legend
Posts: 10,063
Thanks: 674
Fixes: 75
Registered: ‎06-04-2007

Re: PHP: Template script problem with preg_replace

By default PCRE patterns are greedy, with  the result you mentioned. The solution is to use a PCRE-specific modifier '?U' to make them non-greedy.
For your preg_replace this could be specified in two ways
[code=Method1]
$Template = preg_replace('/\<__(.*?U)__\>/', '', $Template);[/code]
[code=Method 2]
$Template = preg_replace('/(?U)\<__(.*)__\>/', '', $Template);[/code]
In your case both methods should give the same result since there is only one quantifier. However Method 1 applies the modifier only within the sub-pattern containing it; Method 2 applies the modifier at top-level so that it applies to all quantifiers throughout the rest of the pattern.
David
David
7up
Community Veteran
Posts: 15,828
Thanks: 1,583
Fixes: 17
Registered: ‎01-08-2007

Re: PHP: Template script problem with preg_replace

I'll give that a try Wink
I need a new signature... i'm bored of the old one!