Home  >  Article  >  Daily Programming  >  What are the methods to achieve string reversal in PHP? (Pictures + Videos)

What are the methods to achieve string reversal in PHP? (Pictures + Videos)

藏色散人
藏色散人Original
2018-10-09 14:06:566017browse

This article mainly introduces several detailed methods to achieve PHP string reversal.

PHP String Reverse It can be said to be a common interview question for PHP job seekers during the interview process. For example, I will ask how to achieve string reversal in PHP? What are the methods? Give examples, etc.

Below we will introduce several methods of PHP string reversal through simple code examples.

Method 1: Use recursion to flip the string

The PHP code example to achieve string reversal is as follows:

<?php
$str = "Hello";
function reversal1($str)
{
    if (strlen($str) > 0) {
        reversal1(substr($str, 1));
    }
    echo substr($str, 0, 1);
    return;
}
reversal1($str);

This paragraph In the code, we just want to reverse the word string "Hello". Here we define a reversal1 method to reverse the string using the principle of recursive algorithm.

The strlen function means to obtain the string length.

The substr function means returning a substring of a string.

The reversal effect is as shown below:

What are the methods to achieve string reversal in PHP? (Pictures + Videos)

So in the previous article [How to implement recursive sorting in PHP? ], the recursive algorithm has been explained in detail. Newbies who don’t know about recursion can refer to it first.

Method 2: Use a for loop to flip the string

<?php
$str = "Hello";
function reversal2($str)
{
    for ($i = 1; $i <= strlen($str); $i++) {
        echo substr($str, -$i, 1);
    }
    return;
}
reversal2($str);

What we need to pay attention to here is that the second one in the substr() function If the parameter is a negative sign, it means intercepting from the first position from the last.

The final effect is the same as method one.

Method 3: Use strrev() PHP function to flip the string

<?php
$str = "Hello";
echo strrev($str);

PHP string reversal function strrev() is the simplest way to reverse a string. Because strrev() is a built-in function in PHP that reverses strings.

The final effect is the same as above.

This article is about three methods to achieve string reversal in PHP.

If you want to know more about PHP, you can follow the PHP Chinese website PHP Video Tutorial, everyone is welcome to refer to and learn!

The above is the detailed content of What are the methods to achieve string reversal in PHP? (Pictures + Videos). 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