Questions & Answers

Using regex to match multiple optional arguments in an enclosed custom function

I'm building a website and I have created a couple of custom functions that add certain information on the page. One of them is as follows:

{{i|Custom argument 1|Custom argument 2|Custom argument 3|...|Custom argument n}}

The number of arguments has no limit, and they all follow the same pattern, starting with |, and finishing with another |, or }} for the last argument.

I'm trying to capture all custom arguments with a RegEx pattern, and them use preg_replace_callback to make the replacements.

I managed to create a RegEx pattern that works with 1 optional argument, but I can't manage to add more. A single pattern to capture all arguments as groups would be the best scenario.


This is my current code that works with 1 mandatory $match[1] and 1 optional argument $match[2]. I'm trying to get the 2nd optional argument $match[3] to work.

$text = preg_replace_callback("{{{i\|(.*?)(?:\|(.*?))?}}}", 
    return '<a href="some_link/'. $match[1] .'><img src="img_dir/'. $match[2] .'.png">'. (isset($match[3]) ? $match[3] : "Default text") .'</a>';
}, $text);
2023-01-20 23:01:08
Why don't you first capture what is between {{....}} and then split on a pipe char?
2023-01-20 23:01:08
That's actually a very smart and simple workaround, and I can even use it to combine all my separate patterns in one. Much appreciated!
Answers(0) :