2009-07-23 78 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 

?> 
相關問題