Home  >  Article  >  Backend Development  >  How to reverse string in PHP

How to reverse string in PHP

藏色散人
藏色散人Original
2021-03-11 10:30:537255browse

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.

How to reverse string in PHP

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  = &#39;&#39;;
$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 = &#39;&#39;;
$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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn