Home > Backend Development > PHP Problem > How to flip a string in php

How to flip a string in php

(*-*)浩
Release: 2023-02-24 14:36:01
Original
1978 people have browsed it

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

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

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

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!

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