=0;$i--){$r.=substr($str,$i,1);}"; 2. Directly use strrev( ) function to reverse a string, syntax "strrev($str)"."/> =0;$i--){$r.=substr($str,$i,1);}"; 2. Directly use strrev( ) function to reverse a string, syntax "strrev($str)".">
Home >Backend Development >PHP Problem >How to reverse string in php
Two methods to achieve string reversal: 1. Use the for statement to traverse the string in reverse order, and use the substr() function in the loop body to intercept characters one by one from back to front, and splice them into a new string. , syntax "$r='';for($i=string length-1;$i>=0;$i--){$r.=substr($str,$i,1);}"; 2. Directly use the strrev() function to reverse the string, the syntax is "strrev($str)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php implements strings Two methods of reversal
Method 1: Using the for statement and substr() function
Use the for statement Traverse the string in reverse order
In the loop body, use the substr() function to intercept characters one by one from back to front and splice them into a new string
Implementation code:
<?php header('content-type:text/html;charset=utf-8'); $str="123456789"; echo "字符串反转前:<br>"; var_dump($str); $result = ''; $len = strlen($str);//获取字符串长度 for ($i = $len-1; $i>=0; $i--){ $result.= substr($str,$i,1); } echo "字符串反转后:<br>"; var_dump($result); ?>
Method 2: Directly use the strrev() function
strrev() is The string reversal function can reverse a string and return the reversed string.
<?php header('content-type:text/html;charset=utf-8'); $str="A123456789B"; echo "字符串反转前:<br>"; var_dump($str); $result = strrev($str); echo "字符串反转后:<br>"; var_dump($result); ?>
Explanation: The
substr() function can intercept a certain length of characters from the specified position of the string. This section is The intercepted characters can be called "substrings" or "substrings", and their syntax format is as follows:
substr($string, $start [, $length])
The parameter description is as follows:
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to reverse string in php. For more information, please follow other related articles on the PHP Chinese website!