This article mainly introduces the PHP string reverse sorting implementation method, and summarizes and analyzes the implementation techniques of strrev function, bipartite, cyclic, recursive, and other commonly used string reverse sorting operations based on the instance form, for more information about how to sort PHP strings in reverse order, see the examples in this article. We will share this with you for your reference. The details are as follows:
For the reverse sorting of strings, the simplest test code for using the PHP function strrev () is as follows:
Header ('content-type: text/html; charset = utf-8 '); $ str = implode ('', range (9, 0); print' <p>Before reversed:'. $ Str. '</p>'; print '<p> <strong> After reversed: </strong> '. strrev ($ str ). '</p>';/* output: Before reversed: 9876543210 After reversed: 0123456789 */
How can I implement strrev () without the built-in PHP function? There are also three methods (bipartite, cyclic, and recursive), but no performance tests are conducted.
(PS: Here we use the online php code formatting tool http://tools.jb51.net/code/jb51_php_formatto help you read the code .)
1. binary classification
/*** Use the binary method to sort strings in reverse order * @ param string $ str Source string * @ return string returns the reverse string */function reverse ($ str = '') {$ len = strlen ($ str); // you 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. circulation method
/*** Use a loop to sort strings in reverse order (efficiency is lower than that of the binary method) * @ param string $ str Source string * @ return string returns the reverse string */function reverse ($ str = '') {$ result = ''; for ($ I = 1; $ I <= strlen ($ str); $ I ++) {$ result. = substr ($ str,-$ I, 1);} return $ result ;}
3. recursion
/*** Recursively arrange strings in reverse order (low efficiency) * @ param string $ str Source string * @ return string returns the reverse string */function reverse ($ str = '') {static $ result = ''; /* use stacks 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 ;}
I hope this article will help you with PHP programming.
For more articles about reverse PHP string sorting, see [strrev function, binary method, loop method, and recursion method!