help with regex expression for PHP

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
lhridley
Forum Newbie
Posts: 2
Joined: Mon Feb 23, 2009 11:06 pm

help with regex expression for PHP

Post by lhridley »

I'm trying to write a regex expression to match variables in a MediaWiki template for a forms extension. The variable in a MediaWiki template can take the following forms:

{{{1}}} --- need to capture "1"
{{{var}}} --- need to capture "var"
{{{var|}}} --- need to capture "var"
{{{var| }}} --- need to capture "var"
{{{var| undefined}}} --- need to capture "var"
{{{var word| undefined}}} --- need to capture "var word"

I've got an expression that's matching everything but the last two options; when I write an expression that catches the fourth option, I lose the first option.

Here's what I have so far:

$b = preg_match_all('/\{\{\{([\w]*?)[\s+]?[\|+]?[\s+]?[a-zA-Z0-9_]?\}\}\}/', $a, $matches);

where \{\{\{([\w]*?)[\s+]?[\|+]?[\s+]?[a-zA-Z0-9_]?\}\}\} is my regex.

Any help provided would be most greatly appreciated. I'd like to do this in one pass if possible, but if I have to write two experssions and merge the results I'll settle for that.

Thank you!
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: help with regex expression for PHP

Post by ridgerunner »

Assuming there is no whitespace between the opening triple curly braces and the first word, this one should do the trick:

Code: Select all

preg_match_all('/(?<=\{\{\{)(\w++(?:\s++\w++)*)/', $contents, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[0]); $i++) {
    # Matched text = $matches[0][$i];
}
Hope this helps! :)
lhridley
Forum Newbie
Posts: 2
Joined: Mon Feb 23, 2009 11:06 pm

Re: help with regex expression for PHP

Post by lhridley »

Sweet! Thank you so much! I'm still testing, but so far that seems to be working.
Post Reply