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.
##1. strrev() flips the string (Recommended learning: PHP Programming From entry to master)
<?php $str = 'Hello World!'; 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 = ''; $str = 'Hello World!'; for($i=1;$i<=strlen($str);$i++){ $newstr.=mb_substr($str,-$i,1); } echo $newstr; #换种方式 $newstr = ''; $str = 'Hello World!'; 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 = ''; $str = 'Hello World!'; $str_arr = str_split($str); for($i=count($str_arr)-1;$i>=0;$i--){ $newstr.=$str[$i]; } echo $newstr
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!