Home  >  Article  >  Backend Development  >  How to flip a string in php

How to flip a string in php

(*-*)浩
(*-*)浩Original
2019-09-20 13:59:521880browse

php flips strings, a test point that often appears in some interview questions. Flip strings in PHP come with the strrev() function. You can also use a for loop with mb_substr() or str_split() to achieve the same function without using PHP's built-in functions.

How to flip a string in php

##1. strrev() flips the string (Recommended learning: PHP Programming From entry to master)

<?php 
$str = &#39;Hello World!&#39;; 
echo strrev($str);

2. for mb_substr() flips the string

The number and position of the for loop, each time mb_substr goes from the end to characters and the process of splicing them together


<?php 
$newstr = &#39;&#39;; 
$str = &#39;Hello World!&#39;;
for($i=1;$i<=strlen($str);$i++){     
    $newstr.=mb_substr($str,-$i,1); 
} 
echo $newstr;
 
#换种方式
$newstr = &#39;&#39;;
$str = &#39;Hello World!&#39;;
for($i=strlen($str);$i>=1;$i--){
    $newstr.=mb_substr($str,$i-1,1);
}
echo $newstr;

3. for str_split() flips the string

str_split() function puts each character of the string into into the array, the for loop traverses the array keys, and the process of splicing the values


<?php 
$newstr = &#39;&#39;; 
$str = &#39;Hello World!&#39;; 
$str_arr = str_split($str); 
for($i=count($str_arr)-1;$i>=0;$i--){     
    $newstr.=$str[$i]; 
} 
echo $newstr

These three methods can eventually flip the string and output the result: !dlroW olleH

The above is the detailed content of How to flip a 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