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

How to reverse string in PHP

藏色散人
Release: 2023-03-08 16:30:02
Original
7304 people have browsed it

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!");
?>
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template