Skip to content

Instantly share code, notes, and snippets.

@Ariflaw
Forked from irazasyed/spintax.php
Created July 11, 2016 06:07
Show Gist options
  • Select an option

  • Save Ariflaw/2d54780ebc9e8bde736bb3087187f191 to your computer and use it in GitHub Desktop.

Select an option

Save Ariflaw/2d54780ebc9e8bde736bb3087187f191 to your computer and use it in GitHub Desktop.

Revisions

  1. @irazasyed irazasyed created this gist Apr 24, 2014.
    34 changes: 34 additions & 0 deletions spintax.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    <?PHP
    /**
    * Spintax - A helper class to process Spintax strings.
    * @name Spintax
    * @author Jason Davis - https://www.codedevelopr.com/
    * Tutorial: https://www.codedevelopr.com/articles/php-spintax-class/
    */
    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)];
    }
    }


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

    /* NESTED SPINNING EXAMPLE */
    echo $spintax->process('{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {{Jason|Malina|Sara}|Williams|Davis}');