Skip to content

Instantly share code, notes, and snippets.

@MarkLL
Forked from irazasyed/spintax.php
Last active September 5, 2015 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MarkLL/5ef760237369303eb26d to your computer and use it in GitHub Desktop.
Save MarkLL/5ef760237369303eb26d to your computer and use it in GitHub Desktop.
<?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/
* Modified by Mark Larsen:
* Added ability so that a fixed output can be returned.
*/
class Spintax
{
protected $useFixedSeed = false;
public function __construct( $bFixed = false, $cSeed = null )
{
if ($bFixed)
{
$this->useFixedSeed = $bFixed;
if (null == $cSeed)
{
$cSeed = $_SERVER['REQUEST_URI'];
}
mt_srand( crc32( $cSeed ) );
}
return $this;
}
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);
// We want the same version returned each time
if ($this->useFixedSeed)
{
// Need to use alternate method of selecting random element
return $parts[ mt_rand(0, count($parts) - 1) ];
}
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}');
/* Example of using Fixed method */
$spintaxFixed = new Spintax( true ); // Using default seed
// Will always bee the same value
echo $spintaxFixed->process($string);
// So will this (but differant to above)
echo $spintaxFixed->process($string);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment