I get bored and I write these functions to screw with strings, like a Cesarean Cipher, substitution cipher, reverse alphabet, and today I made a text shuffler that chops a string in half, and then alternates letters keeping words in tact. So 'Please help me' should become 'Phleel apsm ee' I hope this all makes sense so far. This is working!
However, what I'm trying to figure out, is how to keep punctuation in tact. IE 'Please, help me!' would become 'Phleel, apsm ee!' I just can't seem to figure out how to account for the punctuation... maybe I need to change the way I account for words all together - but I'm lost on this! Here is what I have so far.
<?php
function shuffleText($text) {
// Get the size of each word
$words = explode(' ',$text);
$wrdcnt = count($words);
$wrdsz = array();
for( $i=0; $i<$wrdcnt; $i++ )
$wrdsz[$i] = strlen($words[$i]);
// Shuffle letters
$text = preg_replace('/[\s]+/','',$text);
$temp = str_split($text);
$half = ceil(count($temp) / 2);
$a = array_slice($temp,0,$half);
$b = array_splice($temp,$half);
$text = '';
for( $i=0; $i<$half; $i++ )
$text .= $a[$i] . $b[$i];
if( isset($a[$half]) ) $text .= $a[$half];
// Turn shuffled letters back into words
$start = 0;
$return = '';
for( $i=0; $i<$wrdcnt; $i++ ) {
$return .= substr($text,$start,$wrdsz[$i]) . ' ';
$start += $wrdsz[$i];
}
return trim($return);
}
echo shuffleText('Please help me');