I appreciate the over-arching design of u_mulder's method, but I would like to make some refinements/micro-optimizations for any readers who may be interested.
Code: (Demo)
$string="developer";
$consonants=[];
$length=strlen($string);
for($offset=0; $offset<$length; ++$offset){ // iterate each letter of the string ... OR for($offset=strlen($string); --$offset;){
if(strpos('aeiou',$string[$offset])===false){ // isolate the consonants
$consonants[]=$string[$offset]; // store the consonant
$offsets[]=$offset; // store the offset (aka indexed position of the consonant in the string)
}
}
shuffle($consonants); // shuffle the array of stored consonants
foreach($consonants as $index=>$consonant){ // iterate ONLY the stored consonants
$string[$offsets[$index]]=$consonant; // reassign the consonants in their new positions
}
echo $string; // possible output: revepoled
And here is a blend of array functions with a foreach loop to re-insert the shuffled consonants:
$string="developer";
$consonants=array_diff(str_split($string),['a', 'e', 'i', 'o', 'u']); // isolate consonants, preserve offsets as keys
$offsets=array_keys($consonants); // store copy of offsets before shuffling
shuffle($consonants); // shuffle the array of stored consonants (returned value is re-indexed)
foreach($consonants as $i=>$consonant){
$string[$offsets[$i]]=$consonant; // reassign the shuffled consonants at the known consonant positions
}
echo $string;
For anyone who thinks I don't have any independent ideas to offer... Here is another approach that will implements two string function calls followed by a regex function call (which will negatively impact speed, but not horribly) that may be written as a two-liner.
Code: (Demo)
$word="developer";
$shuffled_consonants=str_shuffle(str_replace(['a','e','i','o','u'],'',$word)); // generate shuffled string of consonants
// reinsert shuffled consonants at original consonant positions
echo preg_replace_callback(
'~[^aeiou]~', // match each consonant at original position
function($m)use($shuffled_consonants){ // pass in the shuffled string
static $offset=0; // init the offset counter
return $shuffled_consonants[$offset++]; // insert new consonant at original position using post-incrementation
},
$word);