PHP: Inline Spintax Function

Published on Author YaniLeave a comment

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)]; 


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.


Categories PHP

Leave a Reply

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