Reverse order of preg_replace() possible?
#1
Well okay, we know that preg_replace() replaces from the start of the string, to the end.
Is it possible to reverse this - ie get it to start replacing from end to start?

If you want a more solid example, this would help with nested bbCodes, for example, if we wanted to remove quotes from a message:
[quote]
test
[quote]inside quote2[/quote]
[/quote]
  random text
[quote]Another quote[/quote]

Using a simple preg_replace() in the above, and replacing with a blank string would obviously cause issues, since it would match the first [quote] with the first [/quote] (assuming we use the "?" modifier; if we don't the first [quote] would match with the last [/quote] which of course, is also problematic).
If the nature could be reversed (short of having to write a custom function), it would actually work...

Possible?
Reply
#2
Well, since no-one responded, here's my dirty method for doing the trick for the above:

// the placeholder is to stop [quo[quote][/quote]te][/quote] from being parsed incorrectly
// assumes that PLACEHOLDER doesn't exist in the string.
define('PLACEHOLDER', "\x00");
while(preg_match('#\[quote(=.*?|)\].*?\[/quote\]#si', $text))
	$text = preg_replace('#(.*)\[quote(=.*?|)\].*?\[/quote\]#si', '$1'.PLACEHOLDER1, $text, 1);
$text = str_replace(PLACEHOLDER1, '', $text);

Probably a bit slow, since preg_replace is called so many times...
Just would be nicer if PHP had some reverse preg_replace... >_>
Reply
#3
I'd think you could use strrev to reverse the string...and I guess you also need to input a reverse regex.
Dennis Tsang
Former MyBB Team Member
Web: http://dennistt.net
Reply
#4
DennisTT Wrote:I'd think you could use strrev to reverse the string...and I guess you also need to input a reverse regex.
You'd have exactly the same problem, because reversing the string won't cause preg_replace to work in reverse - it would match the first [/quote], whereas, you really want it to match the last [quote] first.

Thanks for the answer nonetheless!
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)