PHP Strings Reversing a String by Word or Byte - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Strings Reversing a String by Word or Byte - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Tuesday, May 7, 2019

PHP Strings Reversing a String by Word or Byte

PHP Strings



Reversing a String by Word or Byte


Problem

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

Solution

Example  Reversing a string by byte

              print strrev('This is not a palindrome.');


Example  prints

             .emordnila a ton si sihT


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


Example  Reversing a string by word

              $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 = implode(' ',$words);
               print $s;

Example  prints:

               turtle. a was there time a upon Once


Discussion

Reversing a string by words can also be done all in one line with the code


Example  Concisely reversing a string by word

              $reversed_s = implode(' ',array_reverse(explode(' ',$s)));



No comments:

Post a Comment

Post Top Ad