Skip to content

Instantly share code, notes, and snippets.

@PhiSYS
Forked from irazasyed/spintax.php
Last active April 27, 2020 07:01
Show Gist options
  • Save PhiSYS/4853b297b6386baf4bbc3087c1d925a3 to your computer and use it in GitHub Desktop.
Save PhiSYS/4853b297b6386baf4bbc3087c1d925a3 to your computer and use it in GitHub Desktop.
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