Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

1.4. Reversing a String by Word or Character

Problem

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)));

See Also

Recipe 18.8 discusses the implications of using something other than a space character as your word boundary; documentation on strrev( ) at http://www.php.net/strrev and array_reverse( ) at http://www.php.net/array-reverse.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata