Reverse words in a given string in PHP
In this tutorial, we will learn how to reverse strings and eventually words in a given string in PHP.
It has many built-in methods which can be used for building more dynamic and interactive web pages.
We can reverse a word in a string in PHP in many ways. We will see some of them here.
Basic Usage
Before we see how to reverse words in a string, we will see how to reverse a string in PHP.
Method 1 – Using a for loop
Given below is an illustration for reversing a string using a simple for loop.
<?php #reverseString method function reverseString($inpStr) { echo "The reversed string is: "; for ($i = strlen($inpStr)-1; $i >= 0; $i--) { echo $inpStr[$i]; } echo $revStr; } #driver $inpStr = "CodeSpeedy Technologies"; reverseString($inpStr); ?>
Output
The reversed string is: seigolonhceT ydeepSedoC
Explanation
We use the for loop to index through each character in the string and print it.
Method 2 – Using the built-in method strrev()
Given below is the illustration for reversing a string using strrev() method.
<?php #reverseString method function reverseString($inpStr) { return strrev($inpStr); } #driver $inpStr = "CodeSpeedy Technologies"; echo "The reversed string is: " . reverseString($inpStr); ?>
Output
The reversed string is: seigolonhceT ydeepSedoC
Explanation
We use the built-in method ‘strrev()’ for reversing the string. We create a function named ‘reverseString()’ with the input string as its parameter and return the reverse of the string from it.
Now, we will see how to reverse words in a string. Given below is the illustration for the following to reverse the words in a string.
<?php $inpStr = "CodeSpeedy Technologies"; $inpStrArray = explode(" ", $inpStr); #converting string to array $revArr = array_reverse($inpStrArray); #reversing the array echo "The reversed string words are: " . $revStr = implode(" ", $revArr); #joining the array back to string ?>
Output
The reversed string words are: Technologies CodeSpeedy
Explanation
In the following program, we convert the string to an array by splitting it with spaces. We are reversing the array using the ‘array_reverse()’ method and again joining the array back to form a string to print the reversed words string.
Leave a Reply