スペースで区切られた単語を含む文字列があります。
単語の順序を逆にせずに、すべての単語の文字を逆にしたい。
my string
になりたいym gnirts
です。
これは機能するはずです:
$words = explode(' ', $string);
$words = array_map('strrev', $words);
echo implode(' ', $words);
またはワンライナーとして:
echo implode(' ', array_map('strrev', explode(' ', $string)));
echo implode(' ', array_reverse(explode(' ', strrev('my string'))));
これは、元の文字列を分解した後、配列のすべての文字列を逆にするよりもかなり高速です。
機能化:
<?php
function flipit($string){
return implode(' ',array_map('strrev',explode(' ',$string)));
}
echo flipit('my string'); //ym gnirts
?>
これでうまくいくはずです:
function reverse_words($input) {
$rev_words = [];
$words = split(" ", $input);
foreach($words as $word) {
$rev_words[] = strrev($word);
}
return join(" ", $rev_words);
}
私はするだろう:
$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