Home > Article > Backend Development > How to reverse string by word in php
Reversal method: 1. Use the "explode(' ',$str)" statement to convert the string into an array; 2. Use the "array_reverse($arr)" statement to reverse the array and use the opposite element Return the array in sequence; 3. Use the "implode(' ',$arr)" statement to convert the reversed array into a string.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php will string Reverse by words
Implementation method: Then array
First convert the string into array elements by words
Then use array_reverse() to reverse the array
Then convert the reversed array into a string
implementation Code:
<?php $str = "Reversing a string by word"; // break the string up into words $arr = explode(' ',$str ); // reverse the array of words $arr = array_reverse($arr); // rebuild the string $str = implode(' ',$arr); print $str; ?>
Output result:
Explanation:
explode() function can be based on The string delimiter splits the string, that is, it splits a string into several substrings based on the delimiter, and then combines these substrings into an array and returns it.
array_reverse() function returns an array in reverse element order.
implode() function can convert a one-dimensional array into a string
Recommended learning: "PHP Video Tutorial》
The above is the detailed content of How to reverse string by word in php. For more information, please follow other related articles on the PHP Chinese website!