Examples of url Chinese encoding problems when Curl is used to capture remote content. For URL encoding in PHP, urlencode () or rawurlencode () can be used. The difference between the two is that the former encodes space into +, while the latter encodes space into % 20, however, you should pay attention to the URL encoding in PHP. you can use urlencode () or rawurlencode (). The difference between the two is that the former encodes spaces into '+ ', the latter encodes spaces into '% 20', but it should be noted that only part of the URL should be encoded, otherwise the colon and backslash in the URL will be escaped. The following is a detailed explanation:
The code is as follows:
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:
$ Str = 'boke ';
Echo urlencode ($ str );
Echo"
";
Echo rawurlencode ($ str );
Url result:
The code is as follows:
% 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:
$ 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:
Function cn_urlencode ($ url ){
$ Pregstr = "/[\ x {4e00}-\ x {9fa5}] +/u"; // UTF-8 Chinese regular
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;
}
Url result:
Http://www.baidu.com? Wd = % E5 % 8D % 9A % 20% E5 % AE % A2
Urlencode () or rawurlencode (). The difference between the two is that the former encodes the space into '+', while the latter encodes the space into '% 20', but you should note that...