Monday, March 14, 2011

preg_replace_callback

I am writing Wiki functionality for my game. I want people to be able to post wiki links like [[test]] and have my script auto-link them. A simple preg_replace should do the trick but I want to convert any spaces in the title to a plus (+) sign to prevent the %20 stuff in the URL. So [[wiki link]] should link to ?page=wiki&title=wiki+link. This is where preg_replace_callback comes into play.

This allows you to pass the result of preg_replace to a function and process it's result. In my case this function would replace the spaces to underscores and return that resulting string back to preg_replace.

Here's an example to create wiki links:

<?php
    Function WikiLink ($text) {
        return "<a href=\"?page=wiki&title=".str_replace(" ", "+", $text[1])."\">".$text[1]."</a>";
    }
    Function ReplaceWikiLinks($text){
        $text = preg_replace_callback("#\[\[([a-zA-Z0-9\s]*?)\]\]#si",'WikiLink', $text);
        return $text;
    }
?>

<?php
    // usage
    $text = "This is an [[example]] wiki link.";
    $text = ReplaceWikiLinks($text);
?>

No comments:

Post a Comment