PHP: Find and manipulate the data between delimiters

October 24, 2008

I am currently working on a site where the client has a rich text box to enter content for his articles. This is not unusual in itself, however he wants the ability to do some wikiish syntax in the text box and have the system magically produce the output for him. For instance, \[\[ThisIsSomePage\]\] could create an internal link to some other page on the site. I had not done this before, however I immediately thought of using a regular expression(regex, regexp). A little bit of research confirmed that this would be a good approach, but how was I to get the data between the characters that I chose as delimiters so that I could manipulate it? Turns out that this is a fairly simple and straight forward process.

/**
 * Converts all internal links into html links through the use
 * of a wikiish syntax
 *
 * Syntax for internal links:
 * 		\[\[LinkToSomewhere\]\]
 *
 * Converted to:
 * 		<a href="LinkToSomewhere.html">LinkToSomewhere</a>
 *
 * @param String $text - Text to parse
 * @return String - Parsed text
 */
function convert_internal_links($text)
{
    $text = preg_replace_callback(
                "/\[\[([^\]]+)\]\]/",
                create_function(
                    '$matches',
                    'return "<a href="https://ben.lobaugh.net/blog/wp-admin/%5C%22%22.urlencode%28$matches%5B1%5D%29.%22.html%5C%22">$matches[1]</a>";'
                ),
                $text
            );

    return $text;
}

It works great, and it seems to be pretty quick too.