Example regular expression which was useful in creating a wiki engine
I have a string that looks like,
$str = "This is a [[Link]] that should [[AnotherLink]] get found.";
?>
I want to run a regular expression on this one line that will find text inside the double brackets and will convert it to a link. The result should look like,
This is a <a href="Link">Link</a> that should <a href="AnotherLink">AnotherLink</a> get found.
First, I'll show you the wrong way,
$str = "This is a [[Link]] that should [[AnotherLink]] get found.";
$newstr = preg_replace("/\[\[(.*)\]\]/","<a href=\"\\1\">\\1</a>",$str);
echo($newstr);
?>
The above will spit out,
This is a <a href="Link]] that should [[AnotherLink">Link]] that should [[AnotherLink</a> get found.
The correct code is the following,
$str = "This is a [[Link]] that should [[AnotherLink]] get found.";
$newstr = preg_replace("/\[\[(.*?)\]\]/","<a href=\"\\1\">\\1</a>",$str);
echo($newstr);
?>
Notice that all I added was the question mark on the line that begins with $newstr. This searches for everything inbetween the double brackets, but stops when it finds the first set of ending double brackets (\]\]).
I think this is a non-greedy regular expression - I'm not sure on the terminology there, but that's essentially what it's doing.
The first example without the question mark, found everthing in between the first opening double brackets and the last ending double brackets.
Here's another example that will convert something like,
Go to [[Google Search | http://www.google.com]] to find stuff.
into the following HTML.
Go to <a href="http://www.google.com">Google Search</a> to find stuff.
Here's the code.
$str = "Go to [[Google Search | http://www.google.com]] to find stuff.";
$newstr = preg_replace("/\[\[ *(.*?) *\| *(.*?) *\]\]/","<a href=\"\\2\">\\1</a>",$str);
echo($newstr);
?>
[Click to add or edit comments])
Please prepend comments below including a date