Created
May 7, 2013 10:52
-
-
Save vrushank-snippets/5531800 to your computer and use it in GitHub Desktop.
PHP : Spintax
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 - http://www.codedevelopr.com/ | |
*/ | |
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)]; | |
} | |
} | |
?> | |
<?PHP | |
$spintax = new Spintax(); | |
$string = '{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Davis}!'; | |
echo $spintax->process($string); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, can you help explain the pattern: /{(((?>[^{}]+)|(?R))*)}/x