Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP: Text Spinner Class - Nested spinning supported.
<?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.
* Modified by David Strencsev:
* Refactor and regular expression lazy optimization.
*/
class SpintaxSpinner
{
protected $seed;
public function __construct($seed = null)
{
if (null !== $seed) {
$this->seed = crc32($seed);
}
}
public function execute($spinTemplate)
{
return preg_replace_callback(
'/\{(((?>[^\{\}]+)|(?R))*?)\}/x',
array($this, 'replace'),
$spinTemplate
);
}
private function replace($text)
{
$text = $this->execute($text[1]);
$parts = explode('|', $text);
if ($this->seed) {
// We want the same version returned each time
mt_srand($this->seed);
}
return $parts[mt_rand(0, count($parts) - 1)];
}
}
/* EXAMPLE USAGE */
$spintax = new SpintaxSpinner();
$string = '{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Davis}!';
echo $spintax->execute($string), PHP_EOL;
/* NESTED SPINNING EXAMPLE */
echo $spintax->execute('{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {{Jason|Malina|Sara}|Williams|Davis}'), PHP_EOL;
/* PREDICTABLE EXAMPLE */
$spintax = new SpintaxSpinner('someId');
echo $spintax->execute('{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {{Jason|Malina|Sara}|Williams|Davis}'), PHP_EOL;
echo $spintax->execute('{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {{Jason|Malina|Sara}|Williams|Davis}'), PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment