Haxor
Haxor

Reputation: 621

Reverse each word of a string separately

How can I reverse each word of a string separately using strrev()?

Using strrev(), I'll get the following results:

Input:

Hello world

Output:

dlrow olleH

But the output should be:

olleH dlrow

How can I do this using strrev() or by some other method?

Upvotes: 0

Views: 1091

Answers (3)

Simone Nigro
Simone Nigro

Reputation: 4887

$Str   = 'Hello world';
$Words = preg_split('/\s+/', $Str); // or explode(' ', $Str);

foreach ($Words as $Word)
    echo strrev($Word) . ' ';

output

olleH dlrow 

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76646

Split, reverse, join.

$str = implode(' ', array_map('strrev', explode(' ', $str)));

Tada!

Upvotes: 4

Robin Dorbell
Robin Dorbell

Reputation: 1619

You could split the string using space (' ') as divider, and then strrev each part.

Upvotes: 0

Related Questions