I recently needed to use a “spintax” PHP class for one of my projects. Rather than writing one from scratch, I looked up existing classes and found that Ronald Richardson had already written one that he had released as a free and open source script.
Unfortunately, it looks like his domain has expired, leaving his class unaccessible (I swiped it from Google Cache) so I am reposting the code here for others to use. Again, I had no part in developing this, it was written and released by Ronald Richardson, and is version 3.0 of his Spintax PHP class.
The following code goes in spintax.class.php
<?php
class Spintax {
function spin($str, $test=false) {
if (!$test) {
do {
$str = $this->regex($str);
} while ($this->complete($str));
return $str;
} else {
do {
echo "<b>PROCESS: </b>";var_dump($str = $this->regex($str));echo "<br><br>";
} while ($this->complete($str));
return false;
}
}
function regex($str) {
preg_match("/{[^{}]+?}/", $str, $match);
// Now spin the first captured string
$attack = explode("|", $match[0]);
$new_str = preg_replace("/[{}]/", "", $attack[rand(0,(count($attack)-1))]);
$str = str_replace($match[0], $new_str, $str);
return $str;
}
function complete($str) {
$complete = preg_match("/{[^{}]+?}/", $str, $match);
return $complete;
}
}
?>
And to use it:
<?php
include("spintax.class.php");
$spintax = new Spintax;
// Add true to the spin functions to debug and see each line as it is spun in the process
$spintax->spin("{{Hello|Hi} my name is {Ron|Ronald}|Another random {sentence|{statement|phrase|saying}}}");
?>
Enjoy!
UPDATE: It looks like the original site is back online. You can access the original blog post, with the Spintax code at RonaldRichardson.com.

P.S. I am currently able to accept a limited number of additional clients for my PHP Development services. Interested in discussing the possibility of my handling your project for you? Contact me!
