To encode URLs in PHP, you can use urlencode() or rawurlencode(). The difference between the two is that the former encodes spaces as '+', while the latter encodes spaces as '%20', but it should be noted that , you should only encode part of the URL when encoding, otherwise colons and backslashes in the URL will also be escaped. The following is a detailed explanation:
string urlencode ( string str)
Returns a string in which all non-alphanumeric characters except -_. will be replaced with a percent sign (%) followed by two hexadecimal digits, and spaces are encoded as plus signs ( +).
Example 1: The difference between urlencode function and rawurlencode function
The code is as follows
代码如下 |
复制代码 |
$str='博 客';
echo urlencode($str);
echo " ";
echo rawurlencode($str);
?> |
|
Copy code
|
$str='blog';
echo urlencode($str);
echo " ";
echo rawurlencode($str);
代码如下 |
复制代码 |
$url='http://www.baidu.com/s?wd=博 客';
$arr=explode('=',$url);
$url=$arr[0].'='.rawurlencode($arr[1]);
echo $url;
?>
|
?>
url result:
%B2%A9+%BF%CD
代码如下 |
复制代码 |
function cn_urlencode($url){
$pregstr = "/[x{4e00}-x{9fa5}]+/u";//UTF-8中文正则
if(preg_match_all($pregstr,$url,$matchArray)){//匹配中文,返回数组
foreach($matchArray[0] as $key=>$val){
$url=str_replace($val, urlencode($val), $url);//将转译替换中文
}
if(strpos($url,' ')){//若存在空格
$url=str_replace(' ','%20',$url);
}
}
return $url;
}
echo cn_urlencode($url);
?> |
%B2%A9%20%BF%CD Example 2: URL Chinese encoding method
From url: "http://www.baidu.com/s?wd=blog" to url: http://www.baidu.com/s?wd=%E5%8D%9A%20%E5%AE %A2;
The code is as follows
|
Copy code
|
|
$url='http://www.baidu.com/s?wd=blog';
$arr=explode('=',$url);
$url=$arr[0].'='.rawurlencode($arr[1]);
echo $url;
?>
Result:
http://www.baidu.com/s?wd=%E5%8D%9A%20%E5%AE%A2
Maybe use the following url encoding function
The code is as follows
|
Copy code
|
function cn_urlencode($url){
If(preg_match_all($pregstr,$url,$matchArray)){//Match Chinese, return array<🎜>
foreach($matchArray[0] as $key=>$val){
$url=str_replace($val, urlencode($val), $url);//Replace translation with Chinese
}
If(strpos($url,' ')){//If there are spaces
$url=str_replace(' ','%20',$url);
}
}
Return $url;
}
echo cn_urlencode($url);
?>
url result:
http://www.baidu.com/s?wd=%E5%8D%9A%20%E5%AE%A2
http://www.bkjia.com/PHPjc/629031.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629031.htmlTechArticleTo encode URLs in PHP, you can use urlencode() or rawurlencode(). The difference between the two is that the former Spaces are encoded as '+', while the latter encodes spaces as '%20', but it should be noted...
|
|