PHP Spintax Function

UPDATE: Please use the new improved version PHP Spintax Class HERE

Internet Marketers often use something they call Spintax. Spintax let’s you wrap text in syntax like this {option 1|option 2|option 3} and when processed, it will randomly select one of the text in between the Pipes to show a random text. This function also allows you to nest Spintax inside of other Spintax blocks.

The code is pretty straight forward so I will not go over it, if you have any questions leave a comment…


$str = 'My {spintax|spuntext} formatted string will return {option 1|option 2|option 3}';
echo SpinTax($str);


/**
 * @name SpinTax
 * @var str Text containing our {spintax|spuntext}
 * @return str Text with random spintax selections
 */
function SpinTax($s) {
    preg_match('#{(.+?)}#is',$s,$m);
    if(empty($m)) return $s;

    $t = $m[1];

    if(strpos($t,'{')!==false){
            $t = substr($t, strrpos($t,'{') + 1);
    }

    $parts = explode("|", $t);
    $s = preg_replace("+{".preg_quote($t)."}+is", $parts[array_rand($parts)], $s, 1);

    return SpinTax($s);
}

April 12 2013

Written by

Web-Developer from Central Florida. This blog is my outlet to what I am into at the time. PHP, Javascript, MySQL, OO Practices, Performance, Cool Software and Services, etc... Please subscribe to the RSS feed

  • Nomiguide

    I think if you provide comments for each line it will be easy to understand . from where $m array is coming? :P

    • http://profile.yahoo.com/S64FGY7SRDGLUHFM4U6SZFGXBY Mr

      check out http://us.php.net/preg_match

  • http://twitter.com/iJanErik Jan Erik van Woerden
  • Pingback: PHP Spintax Processor | UmeedainTimes.com

  • http://www.facebook.com/naskootbg Atanas Atanasov

    This is exact what I search. Works with multilevel spin, but characters like ‘ (e.g. it’s). Breaks the code. The solution is to replace ‘ with e.g `

    I get a massage “Fatal error: Maximum function nesting level of ’100′ reached, aborting! in C:wampwwwsindex.php on line 23″ . How can I set higher maximum nesting level?