PHP: Inline Spintax Function

    This was the first PHP oneliner I came up with that spins text around using the well known text spin syntax (Spintax).

     

    function spinText($text){
        return preg_replace_callback(
            '/{(.*?)}/',
            function($matches) { 
                return explode('|', $matches[1])
                    [mt_rand(0, count(explode('|', $matches[1])) - 1)]; 
            }, 
        $text);
    }

     

    Input: Hello {you|mother|father}.

    Output: Hello you. or Hello mother. or Hello father.

     

    preg_replace_callback() is an interesting function as it allows you to cast a function on what’s being returned.

    http://php.net/manual/en/function.preg-replace-callback.php

     

    Leave a Reply

    Your email address will not be published. Required fields are marked *