Skip to content

Instantly share code, notes, and snippets.

@EmilioNicolas
Forked from PhiSYS/spintax.php
Last active October 25, 2020 12:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmilioNicolas/52a19907a40d6f0a021b18b482446179 to your computer and use it in GitHub Desktop.
Save EmilioNicolas/52a19907a40d6f0a021b18b482446179 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 setSeed($seed)
{
srand($seed);
}
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}!"."\n";
echo $spintax->process($string);
/* NESTED SPINNING EXAMPLE */
echo $spintax->process("{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {{Jason|Malina|Sara}|Williams|Davis}")."\n";
/* SET SEED EXAMPLE */
// Sets the seed for the random function. As result, the spin will always output the same text
// no matter how many times you process it. Text Id 100 will always be Hello
$idText = 100;
$spintax->setSeed($idText);
$textId100 = $spintax->process("{Hello|Hi!} {man|guy}")."\n";
echo $textId100;
@EmilioNicolas
Copy link
Author

EmilioNicolas commented Jul 3, 2019

Fork with improved performance and added rand seed configuration for being able to fix the spin. See more in srand manual

Original Gist: https://gist.github.com/irazasyed/11256369

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment