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, it should be noted that only part of the URL should be encoded,
For URL encoding in PHP, urlencode () or rawurlencode () can be used. The difference between the two is that the former encodes spaces into \ '+ \', while the latter encodes the space into \ '% 20 \', it should be noted that during encoding, 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:
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 instance code is as follows:
- $ Str = 'boke ';
- Echo urlencode ($ str );
- Echo"
";
- 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 instance 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 instance code is as follows:
- 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