Skip to content

Instantly share code, notes, and snippets.

@vrushank-snippets
Created May 7, 2013 10:52

Revisions

  1. vrushank-snippets created this gist May 7, 2013.
    31 changes: 31 additions & 0 deletions PHP : Spintax
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    <?PHP
    /**
    * Spintax - A helper class to process Spintax strings.
    * @name Spintax
    * @author Jason Davis - http://www.codedevelopr.com/
    */
    class Spintax
    {
    public function process($text)
    {
    return preg_replace_callback(
    '/\{(((?>[^\{\}]+)|(?R))*)\}/x',
    array($this, 'replace'),
    $text
    );
    }

    public function replace($text)
    {
    $text = $this->process($text[1]);
    $parts = explode('|', $text);
    return $parts[array_rand($parts)];
    }
    }
    ?>

    <?PHP
    $spintax = new Spintax();
    $string = '{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Davis}!';
    echo $spintax->process($string);
    ?>