PHP Reverse a String (original) (raw)
Last Updated : 30 Sep, 2024
**Reversing a string in PHP refers to rearranging a given string's characters in reverse order, starting from the last character to the first. This task is often used in text manipulation or algorithm challenges, highlighting PHP's string-handling capabilities.
**Examples:
Input : GeeksforGeeks
Output : skeeGrofskeeG
Input : 12485
Output : 58421
Below we have discussed about three basic and most commonly used methods of reversing strings in PHP:
Table of Content
- Reversing string using strrev()
- Reversing string using recursion and substr()
- In-place reversing a string without using library functions
**Reversing string using strrev()
The strrev() function in PHP provides a straightforward approach to reversing a string. It takes a string as input and returns a new string with the characters in reverse order, making it an efficient tool for text manipulation.
**Syntax
strrev($string)
**Example :
In this example we defines a Reverse() function that uses strrev() to reverse a given string. The string "GeeksforGeeks" is passed to the function and the reversed result is printed.
PHP `
`
**Reversing string using recursion and substr()
Reversing a string using recursion and substr() involves breaking the string into smaller parts. The substr() function extracts the last character, and recursion reverses the remaining string until it reaches the base case of an empty string, then reassembles it in reverse order.
**Example: In this example we defines a recursive function Reverse() that reverses a string by slicing the first character and appending it to the reversed substring. The base case returns the string when only one character remains.
PHP `
len=strlen(len = strlen(len=strlen(str); // Base case for recursion if($len == 1){ return $str; } else{ $len--; // extract first character and concatenate // at end of string returned from recursive // call on remaining string return Reverse(substr($str,1, $len)) . substr($str, 0, 1); } } // Driver Code $str = "GeeksforGeeks"; print_r(Reverse($str)); ?>`
**In-place reversing a string without using library functions:
In-place string reversal modifies the original string without creating a copy. The approach involves swapping characters from both ends, starting with the first and last, and continuing inward until the middle of the string is reached.
**Example: This PHP function reverses a string in-place by swapping characters from both ends towards the middle, without using library functions. It iterates over the string, exchanging corresponding characters, and returns the reversed string.
PHP `
j=0;j=0; j=0;j<$i; iāā,i--, iāā,j++) { temp=temp = temp=str[$i]; str[str[str[i] = str[str[str[j]; str[str[str[j] = $temp; } return $str; } // Driver Code $str = "GeeksforGeeks"; print_r(Reverse($str)); ?>`