Skip to content

Instantly share code, notes, and snippets.

@Lumbe
Forked from vrushank-snippets/PHP : Spintax
Created November 10, 2020 13:43
Show Gist options
  • Save Lumbe/78e363b012436903e2d2f337dc756dff to your computer and use it in GitHub Desktop.
Save Lumbe/78e363b012436903e2d2f337dc756dff 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);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment