Ok, this is going to be tricky to explain so please bear with me. Basically, I have a string; let's call it $text. Now, within $text, there is a variable number of substrings in the form of "[xxx]...[yyy]", where '...' is an arbitrarily-lengthed string of characters. I am capable of writing a regex expression that will match any occurrence of "[xxx]...[yyy]" in $text. However, I want to formulate an expression such that for each occurrence of "[xxx]...[yyy]", it will also replace certain characters in the '...' section.
Though this wasn't the exact code (I have replaced a few variable names), here was one of my attempts:
Code: Select all
preg_replace("/\[xxx\](.*)\[yyy\]/ie", "'<img src=\"/cgi-bin/script.cgi?'.rawurlencode(str_replace('abc', '123', '$1')", $text);There's probably a ridiculously simple solution that I'll kick myself for not seeing, but at the moment I'm drawing a blank and driving myself insane trying to figure it out. I hope something will understand what I'm asking and know what to do.
Edit: I believe that the reason I'm unable to get this to work is because the text between [xxx] and [yyy] contains at least one newline character, which isn't matched by the (.*) expression. Consequently, no regex match is found at all.
My temporary solution has been to do a str_replace() on the whole string, $text, before the regex to replace all occurrences of '\n' to something the regex can interpret. However, this has the consequence of replacing all occurrences of '\n' in the whole text, not just those between [xxx] and [yyy], so I'm back to square one: trying to replace only the '\n' strings that are contained between [xxx] and [yyy].
Edit 2: I'm an idiot and forgot the PCRE 's' modifier that allows the regex to match newline characters. However, my expression still doesn't parse properly, giving a vague "fatal error" saying that the replacement code, ie. from "<img src=" onwards, fails to evaluate. The expression is now as follows:
Code: Select all
$text = preg_replace("/\[xxx\](.*)\[yyy\]/ies", "'<img src=\"/cgi-bin/script.cgi?'.rawurlencode(str_replace('\n', '\\', '$1'))", $text);