2009-07-23 77 views

回答

6

这应该工作:

$words = explode(' ', $string); 
$words = array_map('strrev', $words); 
echo implode(' ', $words); 

或者作为一个班轮:

echo implode(' ', array_map('strrev', explode(' ', $string))); 
+0

+1:该array_map是一个很好的接触! – 2009-07-23 06:49:17

+3

knahT uoy:o))) – deceze 2009-07-23 06:58:31

2
echo implode(' ', array_reverse(explode(' ', strrev('my string')))); 

这比在爆炸原始字符串之后反转数组的每个字符串要快得多。

+0

确实如此,因为数组函数比字符串函数更快。有关系吗?除非你一次倒转数十亿个字符串。 – deceze 2009-07-23 07:11:32

0

这应该做的伎俩:

function reverse_words($input) { 
    $rev_words = []; 
    $words = split(" ", $input); 
    foreach($words as $word) { 
     $rev_words[] = strrev($word); 
    } 
    return join(" ", $rev_words); 
} 
0

我会做:

$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 
1

Functionified:

<?php 

function flipit($string){ 
    return implode(' ',array_map('strrev',explode(' ',$string))); 
} 

echo flipit('my string'); //ym gnirts 

?> 
相关问题