PHP built-in function is not used intval (), to achieve the string to Integer

Usually when we use when PHP, a string into an integer, generally used intval () built-in function, so if we ourselves write, how to write one do?

At this point we can use the characteristics of the ASCII code calculated integer, because each character corresponds to an ASCII code, when this character to do addition, subtraction when, in fact, on the ASCII code to add and subtract, multiply and divide operations, that is, integer operation, will eventually return an integer number.

That is:
'1' - '0' = 1;
2 '' - '0' = 2;

Numbers 0 to 9 decimal ASCII equivalent of:

An ASCII value of 
048 1 49 2 50 3 51 4 52 5 53 6 54 7 55 8 56 9 57

Similarly the intval () function is implemented method:

// custom string transfected int 
function myIntval ( $ STR = '' )
{
    len $ = strlen ( $ STR );
     $ int = 0 ;
     $ negative = to false ; // if negative 
    for ( $ I = 0; $ I < $ len ; $ I ++ ) {
         // the first character is determined negative 
        IF ( $ I == 0 ) {
             IF ( $ STR [ $ I ] == '-' ) {
                 $ negative = to true ;
                 Continue ;
            }
        }
        // Analyzing the character ASCII code is not numeric range 
        IF ( $ STR [ $ I ] < '0' || $ STR [ $ I ]> '. 9' ) {
             BREAK ;
        }

        int $ * = 10 ;
         $ NUM = $ STR [ $ I ] - '0'; // subtracting the ASCII code number itself is 0 [int type] 
        $ int = $ int + $ NUM ;
    }
    $int = $negative === true ? -$int : $int;
    return $int;
}

var_dump (myIntval ( '- 1tt01t34t')); // Output: int (-1) 
var_dump (myIntval ( '- tt01t34t')); // Output: int (0) 
var_dump (myIntval ( 'tt01t34t')); / / output: int (0) 
var_dump (myIntval ( '01t34t')); // output: int (. 1) 
var_dump (myIntval ( '134t')); // output: int (134)

 

Note:

Transfer function string integer Redis is also achieved with minus-based ASCII.

 

Guess you like

Origin www.cnblogs.com/deverz/p/11076453.html