Doubt I'll ever be able to use regex properly. What I need is a regex that will match: Spoiler Text And: Spoiler: Title Text And: Spoiler: Title Text And: Spoiler: Title Text I've tried all sorts of crap, but since I just can't wrap my head around regex, I doubt any of it was real regex. Now I am sick of saying regex. Thank you, Josh
'~\[spoiler(?:[ ]?=[ ]?(["\'])?([^"\'\]]+)\1?)?\](.*?)\[/spoiler\]~si' PHP: Regex isn't that hard once you know the basics. Check: www.phpvideotutorials.com/regex/
Thanks. Halfway through the video now Still a little confused though, cause now nothing is showing up in the replace. I thought the title would come out as $1 and the inner text would be $2, but it doesn't seem so :S EDIT: Its $2 and $3. Got it. Thanks again
Just for clarification: The first group starts with a colon followed by a question mark ?), which means this group won't be captured in the $matches array.
Cool. And just curious (always wondered about regex, since you can't directly manipulate the "variables" afaik. Can you have it, so that if a group is empty, replace it with something else?
Say, using my example, if we have Spoiler: Hello Test It outputs something like: Hello<br/>Test Code (markup): But if we just had Spoiler Test The output would be: <br/>Test Code (markup): And say I wanted a default value - such as "Title". Then if I had Spoiler Test it would output: Title<br/>Test Code (markup): So just a default for one of the matches really...
I don't think that's possible to specify directly in the regular expression itself. But I guess you could do something like: $pattern = '~\[spoiler(?:[ ]?=[ ]?(["\'])?([^"\'\]]+)\1?)?\](.*?)\[/spoiler\]~si'; $text = preg_replace_callback($pattern, '__callback_handler', $text); function __callback_handler($matches) { return sprintf("%s<br />\n%s", !empty($matches[2]) ? $matches[2] : 'Title', !empty($matches[3]) ? $matches[3] : 'Default' ); } PHP:
Ahh, I ended it up doing a longer way - easier to understand, but may not be as efficient. I used a another preg_replace() to replace any one with no attribute with one that does have an attribute. So Spoiler or Spoiler become Spoiler: Title Thanks BP