How to reverse text in php

藏色散人
Release: 2023-03-13 17:44:02
Original
1984 people have browsed it

How to achieve text reversal in php: 1. Use the strrev function to achieve the reversal; 2. Reverse by dividing the string into an array, and then traverse and splice it; 3. Use recursion to achieve the reversal change.

How to reverse text in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How to reverse text in php?

Three ways to reverse strings in php

(Assume there is a string abcd, use php to reverse the string)

1. The first type of php has its own function strrev that can be easily implemented:

$str = 'abcd';
//第一种自带strrev实现翻转
echo strrev($str);
Copy after login

Output effect:

2. Just split the string into one array, and then traverse and splice:

function joinStrrev($str){
        if (strlen($str) <= 1) return $str;

        $newstr  = &#39;&#39;;
        //str_split(string,length) 函数把字符串分割到数组中:string 必需。规定要分割的字符串。length     可选。规定每个数组元素的长度。默认是 1。
        $strarr = str_split($str,1);
        foreach ($strarr as $word) {
            $newstr = $word.$newstr;
        }
 
        return $newstr;
    }

$revstr = joinStrrev($str);
echo $revstr;
Copy after login

Output effect:

3. Just use recursion to do it:

function recursionStrrev($str){        if (strlen($str) <= 1) return $str;//递归出口         $newstr = &#39;&#39;;        //递归点,substr(string,start,length) :substr() 函数返回字符串的一部分,如果 start 参数是负数且 length 小于或等于 start,则 length 为 0,正数 - 在字符串的指定位置开始,负数 - 在从字符串结尾的指定位置开始,0 - 在字符串中的第一个字符处开始        $newstr .= substr($str,-1).recursionStrrev(substr($str,0,strlen($str)-1));         return $newstr;//递归出口    }    $revstr = recursionStrrev($str);    echo $revstr;
Copy after login

Output effect:

Recommended study: "PHP Video Tutorial"

The above is the detailed content of How to reverse text in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!