Instance
Returns the ASCII value of "H":
<?phpecho Ord ("H"). " <br> "; Echo ord (" Hello ")." <br> ";? >
Definition and usage
The Ord () function returns the ASCII value of the first character in a string.
Grammar
Ord (String)
Parameter description
string is required. The string from which to get the ASCII value.
Technical details
Return value: Returns the ASCII value as an integer.
PHP version: 4+
The application of the Ord () function
The Ord () function is used to return the ASCII value of a character, the most basic usage of which is to get the ASCII value of a, Ord (' a ') returns 97, but in actual development, the most used is to get the decimal number of the Chinese characters in the character intercept function. such as the common Chinese character interception function can see the phpwind or discuz! forum source code in the Substrs () function or the CUTSTR () function, the principle is to get the ASCII value of the character through the Ord () function, if the return value greater than 127 is expressed as half of Chinese characters, The second half is combined into a full character, combined with character encoding such as GBK or UTF-8.
Using the Ord () function to determine the ASCII value of the Chinese characters returned by the GBK encoding, the code is as follows
$string = "Don't be infatuated with elder brother"; $length = strlen ($string); Var_dump ($string);//original Chinese var_dump ($length);//Length $result = Array (); for ($i =0; $i < $length; $i + +) {if (Ord ($string [$i]) >127) {$result [] = $string [$i]. ' '. $string [+ + $i]; }} var_dump ($result);
Code description
1, define a variable $string, whose value is a string
2, gets the length of the variable (in bytes)
3, the length of the print variable and variable
4, through the for loop to get the individual byte value of the variable, the middle of the two bytes of a Chinese character separated by a space display.
Results such as
Plot: "Do not crush elder brother" for 5 characters, a total of 10 bytes (a Kanji 2 bytes), respectively print the individual bytes can not display as normal as
Initial value unchanged modify for loop part code display individual bytes ASCII value
$result = Array (); for ($i =0; $i < $length; $i + +) {if (Ord ($string [$i]) >127) {$result [] = Ord ($string [$i]). ' '. Ord ($string [+ + $i]); }} var_dump ($result);
As the above code uses the Ord () function to print the ASCII values of each character, the results are as follows
The ASCII value of each character can be viewed normally after conversion with the Ord () function.