This article mainly introduced the PHP string in reverse order implementation method, combined with the example form summarizes and analyzes the Strrev function, the dichotomy method, the cyclic method, recursive method and so on commonly used string reverse arrangement operation Realization Skill, needs the friend to refer to the next
Specific as follows:
The simplest test code for using the PHP function, Strrev (), is in reverse order of the string:
Header (' content-type:text/html; Charset=utf-8 '); $str = Implode (", Range (9, 0));p rint ' < P><strong>before Reversed: </strong> '. $str. ' </p> ';p rint ' < p>< Strong>after reversed: </strong> '. Strrev ($STR). ' </p> ';/* output is as follows: Before Reversed:9876543210after reversed:0123456789*/
What if we don't use the built-in PHP function Strrev ()? There are 3 different methods (dichotomy, cyclic, recursive), but no performance tests are performed.
1. Dichotomy
/*** binary method to implement strings in reverse order * @param string $STR The source string * @return string returns the inverse of the strings */function reverse ($str = ") { $len = strlen ($STR); //cannot use count or sizeof $mid = Floor ($len/2); for ($i =0; $i < $mid; $i + +) { $temp = $str [$i]; $STR [$i] = $str [$len-$i-1]; $str [$len-$i-1] = $temp; } return $STR;}
2. Cyclic method
The/*** loop implements an inverse arrangement of strings (less efficient than dichotomy) * @param string $STR The source string * @return string returns the strings after reverse order */function reverse ($str = ") { $result = ''; for ($i =1; $i <=strlen ($STR), $i + +) { $result. = substr ($str,-$i, 1); } return $result;}
3. Recursive method
/*** recursive implementation of strings in reverse order (inefficient) * @param string $STR The source string * @return string back to reverse the strings */function reverse ($str = ") { static $resul t = '; /* Use the stack to understand recursive calls */ if (strlen ($STR) > 0) { reverse (substr ($STR, 1)); $result. = substr ($str, 0, 1); This sentence must be placed after the previous statement } return $result;}
The above is the whole content of this article, I hope that everyone's study has helped.