We are using
For the reverse sorting of strings, the test code of the PHP function strrev () is as follows:
- Header ('content-type: text/html; charset = UTF-8 ');
- $ Str = implode ('', range (9, 0 ));
- Print '<p> <strong> Before reversed: </strong>'. $ str. '</p> ';
- Print '<p> <strong> After reversed: </strong>'. strrev ($ str). '</p> ';
- /*
- The output is as follows:
- Beforereversed: 9876543210
- After reversed: 0123456789
- */
How can I implement strrev () without the built-in PHP function? Three methods (bipartite, cyclic, and recursive) were tested, but no performance tests were conducted.
1. binary classification
- /**
- * The binary method is used 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
- /**
- * Cyclically arrange 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); // The sentence must be placed after the previous statement.
- }
- Return $ result;
- }
The above is the specific usage of the PHP function strrev () and the implementation of the other three methods in reverse order.