View Full Version : Stupid Regex. Need help again.
blueparukia
Jul 19th 2008, 12:35 am
Doubt I'll ever be able to use regex properly.
What I need is a regex that will match:
Text
And:
Text
And:
Text
And:
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
nico_swd
Jul 19th 2008, 1:20 am
'~\[spoiler(?:[ ]?=[ ]?(["\'])?([^"\'\]]+)\1?)?\](.*?)\[/spoiler\]~si'
Regex isn't that hard once you know the basics. Check: www.phpvideotutorials.com/regex/
blueparukia
Jul 19th 2008, 1:49 am
Thanks. Halfway through the video now :D
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
nico_swd
Jul 19th 2008, 1:56 am
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.
blueparukia
Jul 19th 2008, 1:59 am
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?
nico_swd
Jul 19th 2008, 2:02 am
I don't think I understand your question. Can you give me an example?
blueparukia
Jul 19th 2008, 2:07 am
Say, using my example, if we have
Test
It outputs something like:
Hello<br/>Test
But if we just had Test
The output would be:
<br/>Test
And say I wanted a default value - such as "Title".
Then if I had
Test
it would output:
Title<br/>Test
So just a default for one of the matches really...
nico_swd
Jul 19th 2008, 2:22 am
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'
);
}
blueparukia
Jul 19th 2008, 2:29 am
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
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.