String urlencode (string str)
Returns a string -_. all other non-alphanumeric characters will be replaced with a semicolon (%) followed by two hexadecimal numbers, and spaces will be encoded as the plus sign (+ ).
Example 1: Difference between urlencode and rawurlencode
The code is as follows: |
Copy code |
<? Php $ Str = 'boke '; Echo urlencode ($ str ); Echo "<br> "; Echo rawurlencode ($ str ); ?> |
Url result:
% B2 % A9 + % BF % CD
% B2 % A9 % 20% BF % CD Example 2: url Chinese encoding method
From url: "http://www.baidu.com/s? Wd = blog "convert to url: http://www.baidu.com/s? Wd = % E5 % 8D % 9A % 20% E5 % AE % A2;
The code is as follows: |
Copy code |
<? Php $ Url = 'http: // www.baidu.com/s? Wd = boke '; $ Arr = explode ('=', $ url ); $ Url = $ arr [0]. '='. rawurlencode ($ arr [1]); Echo $ url; ?> |
Result:
Http://www.baidu.com? Wd = % E5 % 8D % 9A % 20% E5 % AE % A2
Use the following url encoding function
The code is as follows: |
Copy code |
<? Php Function cn_urlencode ($ url ){ $ Pregstr = "/[x {4e00}-x {9fa5}] +/u"; // UTF-8 Chinese regular expression If (preg_match_all ($ pregstr, $ url, $ matchArray) {// matches Chinese characters and returns an array Foreach ($ matchArray [0] as $ key => $ val ){ $ Url = str_replace ($ val, urlencode ($ val), $ url); // replace translation with Chinese characters } If (strpos ($ url, '') {// if space exists $ Url = str_replace ('', '% 20', $ url ); } } Return $ url; } Echo cn_urlencode ($ url ); ?> |
Url result:
Http://www.baidu.com? Wd = % E5 % 8D % 9A % 20% E5 % AE % A2