views:

543

answers:

6

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'

+6  A: 

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)));
deceze
+1: The array_map is a nice touch!
David Schmitt
knahT uoy :o)))
deceze
+2  A: 
echo implode(' ', array_reverse(explode(' ', strrev('my string'))));

This is considerably faster than reversing every string of the array after exploding the original string.

Kevin
True, as array functions are faster than string functions. Does it matter? Not unless you're reversing a few billion strings at once.
deceze
A: 

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);
}
David Schmitt
`split()` is part of the POSIX Regex extension, and is deprecated in PHP 5.3.0 in favour of Perl-Compatible Regex (PCRE). But you don't need regex anyway, you just need `explode()`.
too much php
Ah, good to know, thanks.
David Schmitt
A: 

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
FWH
+1  A: 

Functionified:

<?php

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

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

?>
cpharmston
A: 

There is a built-in function strrev

Bakudan