Page 1 of 1

preg_replace replacing wrong part

Posted: Wed Feb 27, 2008 6:25 pm
by Acid X
Alright so, heres my code:

Code: Select all

<?php
$string = "[x| 5d4fa6sd8f34344w REPLACE_THIS 11321225 |x] asdfasdfds [x| 5d4fa6sd8f34344w REPLACE_THIS 11321225 |x]  ddf3a33  [x| 5d4fa6sd8f34344w REPLACE_THIS 11321225 |x]";
echo preg_replace("/\[x\|(.*)REPLACE_THIS(.*)\|x\]/","\\1 BLAH \\2", $string); 
?>
In case you can't tell, what i'm trying to do is pull the surrounds of the word REPLACE_THIS out from around it. Not including the [x| and |x] things.

What i'm trying to do is define a point in a template to replace that string but it needs to be surrounded by those designs and have a certain word in the center.

IE:

[x| <*> REPLACE_THIS <*> |x]

I'm trying to replace that, but still using the design around the words, so it would look like this:

<*> BLAH <*>

Whats going on, is, as you can see i have $string set to an example, but with multiple copies. Whats going on, if you haven't figured it out already, is that instead of only replacing the first entry, it sees most of the entry as the first (.*) in my expression. It prints out like this:

5d4fa6sd8f34344w REPLACE_THIS 11321225 |x] asdfasdfds [x| 5d4fa6sd8f34344w REPLACE_THIS 11321225 |x] ddf3a33 [x| 5d4fa6sd8f34344w BLAH 11321225

What am i doing wrong? Also note that i put something in between each to try to spread them apart, but it still picks up the expression all the way to the end.

Eventually i plan to make a LOOP that uses the replace method to replace every instance of this throughout the page, but at this point in the code its going to replace everything in between the first and last one thinking that everythign in between is part of the first expression.

Anyway, if you understood me, i'd appreciate some help!

EDIT: Also i should note that i was trying to make it so \\1 and \\2 could contain ANY character, so stopping a string from registering needs to happen without actually barring certain characters from use.. I was thinking something along the lines of ([^\|x\]]*) - This works and solves my problem *except* the characters "|" "x" and "]" can't be used in \\1 or \\2 and then would cause a problem at a later date if the user wanted to use those characters as part of the template.

Re: preg_replace replacing wrong part

Posted: Wed Feb 27, 2008 9:11 pm
by Acid X
Ok well i was able to get some external help! But what fixed it was changing (.*) to (.+?) -- Just incase anyone was interested.

Re: preg_replace replacing wrong part

Posted: Wed Feb 27, 2008 11:18 pm
by John Cartwright
By default, your regex is greedy and will match as much as possible. Using the ? in .*? makes it non-greedy

Re: preg_replace replacing wrong part

Posted: Thu Feb 28, 2008 2:04 pm
by Jonah Bron
Yeah. Always use *?