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!
help with regex expression for PHP
Moderator: General Moderators
- ridgerunner
- Forum Contributor
- Posts: 214
- Joined: Sun Jul 05, 2009 10:39 pm
- Location: SLC, UT
Re: help with regex expression for PHP
Assuming there is no whitespace between the opening triple curly braces and the first word, this one should do the trick:
Hope this helps! 
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];
}Re: help with regex expression for PHP
Sweet! Thank you so much! I'm still testing, but so far that seems to be working.