Oleh: dgtola | 1 November 2009

Reversing a String by Word or Character

You want to reverse the words or the characters in a string.

Solution

Use strrev( ) to reverse by character:

print strrev(‘This is not a palindrome.’);
.emordnilap a ton si sihT

To reverse by words, explode the string by word boundary, reverse the words, then rejoin:

$s = “Once upon a time there was a turtle.”;
// break the string up into words
$words = explode(‘ ‘,$s);
// reverse the array of words
$words = array_reverse($words);
// rebuild the string
$s = join(‘ ‘,$words);
print $s;
turtle. a was there time a upon Once

Discussion

Reversing a string by words can also be done all in one line:
$reversed_s = join(‘ ‘,array_reverse(explode(‘ ‘,$s)));

#php Cookbook#


Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

Kategori

%d blogger menyukai ini: