Simple PHP text Spinner

A while back someone asked me how would you go about writing a text spinner in PHP code.

It simple enough, you need to work with { | } and random numbers, I have done various forms of this in my time but mostly in .NET C#.

Here is the sample code I came up with for a simple text spinner in PHP, I’ve added some comments through the code to try and explain what is going on at each stage and way.

Hopefully, it’s all self-explanatory and easy to understand.

Simple PHP text Spinner

//First we need to build an array of text to spin
$text2spin = "{hello|hi|howdy|morning|afternoon} my name is Myles, {i am|i'm} a {super|lovely|great|marvelous|wonderful} {person|bloke|admin|god like being}!";

//Now we create a basic function to spin the words and return them
function spin($text) {

//Break the text array into words/chunks so we can spin them 
preg_match_all('!{(.*?)}!s', $text, $matches);

//Loop through all the words to build up some replacements
foreach($matches[0] as $key => $match)
{
//Split the chunks 
$words = explode("|", $matches[1][$key]);

//the word we want to replace
$find[] = $match;

//generate a random number from the size of the chunk and grab a word
$replace[] = $words[mt_rand(0, count($words) - 1)];
}

// now loop through our words we want to replace 
foreach($find as $key => $value)
{

//get the position of the word to replace in the string
$pos = mb_strpos($text, $value);

//replace the word
$text = mb_substr($text, 0, $pos).$replace[$key].mb_substr($text, $pos + mb_strlen($value));

}
//return our spun text
return $text;

}

//Call our function to spin the text and output to screen
echo spin($text2spin);

?>

Happy coding folks.

Like this post?

Why not drop leave a comment and let me know if you used the code or found it helpful.