Skip to content

Instantly share code, notes, and snippets.

@amrikarisma
Forked from irazasyed/spintax.php
Created September 3, 2017 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amrikarisma/8e853ecd147f1413b041ddc1886776f2 to your computer and use it in GitHub Desktop.
Save amrikarisma/8e853ecd147f1413b041ddc1886776f2 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/
*/
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}');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment