Skip to content

Instantly share code, notes, and snippets.

@vrushank-snippets
Created May 7, 2013 10:52
Show Gist options
  • Save vrushank-snippets/5531800 to your computer and use it in GitHub Desktop.
Save vrushank-snippets/5531800 to your computer and use it in GitHub Desktop.
PHP : Spintax
<?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);
?>
@NealWalters
Copy link

Thanks, can you help explain the pattern: /{(((?>[^{}]+)|(?R))*)}/x

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