PHP Functions: Wiggle, Wobble, Squibble & Swipswap
Here are a few fun functions for word games, word scrambling and just plain word craziness.
<?php
/***********
* Purpose: move a certain letter to a certain position
* Precondition: word, letter to move, position to move it to
* Postcondition: word has been re-arranged
***********/
function wiggle($word, $letter, $position = 0)
{
$word = str_replace(" ", "_", $word);
if ($start = strpos($word, $letter))
{
$array = array_merge(str_split(substr($word, 0, $start)), str_split(substr($word, $start+1, strlen($word))));
for ($i = 0; $i < strlen($word); $i++)
{
if ($i != $position)
$final .= $array[$i];
else
$final .= $letter . $array[$i];
}
return str_replace("_", " ", $final);
}
else
return; //letter wasn't found
}
/***********
* Purpose: move the letter at a certain position to a new position
* Precondition: word, position to move from, position to move to
* Postcondition: letter has moved from start to end position
***********/
function wobble($word, $start, $position = 0)
{
$word = str_replace(" ", "_", $word);
$start -= 1;
$array = array_merge(str_split(substr($word, 0, $start)), str_split(substr($word, $start+1, strlen($word))));
for ($i = 0; $i < strlen($word); $i++)
{
if ($i != $position)
$final .= $array[$i];
else
$final .= substr($word, $start, 1) . $array[$i];
}
return str_replace("_", " ", $final);
}
/***********
* Purpose: move letters from this position and on to the beginning of the word
* Precondition: word, position to start from
* Postcondition: words from start to strlen($word) are not at the beginning of the word
***********/
function jiggle($word, $start)
{
return substr($word, $start, strlen($word)-$start) . substr($word, 0, $start);
}
/***********
* Purpose: replace all $letters in the word with $replace
* Precondition: word, letter you want replaced, letter to replace it with
* Postcondition: word has been re-arranged
***********/
function swipswap($word, $letter, $replace)
{
return str_replace($letter, $replace, $word);
}
/***********
* Purpose: every $length move the following $number of letters to the beginning of the word
* Precondition: word, lengh between squiggles, number of letters to move
* Postcondition: word has been re-arranged
***********/
function squiggle($word, $length = 1, $number = 2)
{
if ($length >= strlen($word))
$word = strrev($word);
else
{
for ($i = 0; $i < strlen($word); $i++)
{
if ($i % $length)
$word = substr($word, $i, $number) . substr($word, 0, $i) . substr($word, $i+$number, strlen($word));
} //end for
}//end else
return $word;
}
//test it out!
echo wiggle("Hey Johnny 21", "e", 6);
echo "<br/>";
echo wobble("Hey Johnny 21", 3, 6);
echo "<br/>";
echo jiggle("Hey Johnny 21", 3);
echo "<br/>";
echo squiggle("Hey Johnny 21", 2, 2);
echo "<br/>";
echo swipswap("Hey Johnny 21", "n", "d");
?>
