-
-
Save riedayme/6b8b94e8d6c29977574d7a31732d7072 to your computer and use it in GitHub Desktop.
PHP: Text Spinner Class - Nested spinning supported.
This file contains 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. | |
* | |
* @author Jason Davis - https://www.codedevelopr.com/ | |
* | |
* Tutorial: https://www.codedevelopr.com/articles/php-spintax-class/ | |
* | |
* Updated with suggested performance improvement by @PhiSYS. | |
*/ | |
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