1. 给一个句子,翻转每个单词,单词内部不翻转
$str = "dog loves pig";
$ret = turnSentence($str);
var_dump($ret);
function turnSentence($str1)
{
$str2 = turnWord($str1);
$str2_arr = explode(' ', $str2);
foreach ($str2_arr as $key => &$value) {
$value = turnWord($value);
}
unset($value);
return implode(' ', $str2_arr);
}
function turnWord($str) // 用php处理字符串函数strrev更优
{
$length = strlen($str);
$ret = '';
for ($i = $length - 1; $i >= 0; $i--) {
$ret .= $str{$i};
}
return $ret;
}
输出结果: pig loves dog