Home > Article > Backend Development > php reverse string method
During the interview for PHP-related jobs, we are likely to encounter this problem, how to reverse a string. Below we will answer this question for you.
Recommended tutorial: PHP video tutorial
##Method 1
Grammar strrev(string)
Example
<?php echo strrev("Hello World!"); ?>
Output: !dlroW olleH
Method 2
Split the string into an array, and then traverse and splice it, as followsfunction revstr($str) { if (strlen($str) <= 1) return $str; $newstr = ''; $str2arr = str_split($str,1); foreach ($str2arr as $word) { $newstr = $word.$newstr; } return $newstr; }
Method 3## Use recursion, the code is as follows
function revstr($str) { if (strlen($str) <= 1) return $str; $newstr = ''; $newstr .= substr($str,-1).revstr(substr($str,0,strlen($str)-1)); return $newstr; }
ps: This method should be what the interviewer wants to see Answer.
The above is the detailed content of php reverse string method. For more information, please follow other related articles on the PHP Chinese website!