-
-
Save GiancarloJSantos/8977de39da8c34e35a389aebc080caea to your computer and use it in GitHub Desktop.
PHP: Text Spinner Class - Nested spinning supported.
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. | |
*/ | |
class Spintax | |
{ | |
/** | |
* Set seed to make the spinner predictable. | |
*/ | |
public function seed(mixed $seed) | |
{ | |
mt_srand(crc32($seed)); | |
} | |
public function process(string $text) | |
{ | |
return preg_replace_callback( | |
'/\{(((?>[^\{\}]+)|(?R))*?)\}/x', | |
function ($match) { | |
$text = $this->process($match[1]); | |
$parts = explode('|', $text); | |
return $parts[mt_rand(0, count($parts) - 1)]; | |
}, | |
$text | |
); | |
} | |
/** | |
* If you want highest randomness, | |
* this is the method to use. | |
* Note: Seed has no effect. | |
* | |
* Last updated: 2023-10-26 | |
*/ | |
public function spin(string $text) | |
{ | |
$pattern = '/{([^{}]+)}/'; | |
while (preg_match($pattern, $text)) { | |
$text = preg_replace_callback($pattern, function ($matches) { | |
$options = explode('|', $matches[1]); | |
return $options[ random_int(0, count($options) - 1) ]; | |
}, $text); | |
} | |
return $text; | |
} | |
} | |
/* 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