i have a string .
i want to reverse the letters in every word not reverse the words order.
like - 'my string'
should be
'ym gnirts'
i have a string .
i want to reverse the letters in every word not reverse the words order.
like - 'my string'
should be
'ym gnirts'
This should work:
$words = explode(' ', $string);
$words = array_map('strrev', $words);
echo implode(' ', $words);
Or as a one-liner:
echo implode(' ', array_map('strrev', explode(' ', $string)));
echo implode(' ', array_reverse(explode(' ', strrev('my string'))));
This is considerably faster than reversing every string of the array after exploding the original string.
This should do the trick:
function reverse_words($input) {
$rev_words = [];
$words = split(" ", $input);
foreach($words as $word) {
$rev_words[] = strrev($word);
}
return join(" ", $rev_words);
}
I would do:
$string = "my string";
$reverse_string = "";
// Get each word
$words = explode(' ', $string);
foreach($words as $word)
{
// Reverse the word, add a space
$reverse_string .= strrev($word) . ' ';
}
// remove the last inserted space
$reverse_string = substr($reverse_string, 0, strlen($reverse_string) - 1);
echo $reverse_string;
// result: ym gnirts
Functionified:
<?php
function flipit($string){
return implode(' ',array_map('strrev',explode(' ',$string)));
}
echo flipit('my string'); //ym gnirts
?>