How to reverse strings in PHP: 1. Reverse the string through the strrev function that comes with PHP; 2. Split the string into an array, and then traverse and concatenate it to reverse the string; 3. , just use recursion to reverse the string.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
Three ways of php reversing strings Method
Method 1: PHP has its own function strrev that can be easily implemented:
Reverse the string "Hello World!":
<?php echo strrev("Hello World!"); ?>
Method 2: Split the string into an array, and then traverse and splice it, as follows:
function 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: This method is the easiest to think of. In addition, there is another method, which is to use recursion. Code 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 the answer the interviewer wants to see.
[Recommended learning: "PHP Video Tutorial"]
The above is the detailed content of How to reverse string in PHP. For more information, please follow other related articles on the PHP Chinese website!