Search code examples
phpstringspinning

Content Spinning using PHP?


Can anyone please help me? Say if I had this text or a smaller section stored in a variable, how can I randomise the words in the '{ }' ?
For example, the first one is "{important|essential|crucial|critical|vital|significant}" how can I make PHP choose one of those words randomly and then echo it? Thanks for helping me. :)


Solution

  • http://webarto.com/62/random-sentence-spinning-function

    function get_random($matches)
    {
        $rand = array_rand($split = explode("|", $matches[1]));
        return $split[$rand];
    }
    
    function show_randomized($str)
    {
        $new_str = preg_replace_callback('/\{([^{}]*)\}/im', "get_random", $str);
        if ($new_str !== $str) $str = show_randomized($new_str);
        return $str;
    }
    

    Applied on your text file... http://ideone.com/rkuf6