-
-
Save lury/113ba31c1a914175a595 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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