PHP中对于URL进行编码,可以使用 urlencode() 或者rawurlencode(),二者的区别是前者把空格编码为 \'+\',而后者把空格编码为 \'%20\',不过应该注意的是,在编码时应该只对部分URL编码,否则URL中的冒号和反斜杠也会被转义。下面是详细解释:
string urlencode ( string str)
返回字符串,此字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。
例子 1 :urlencode函数与rawurlencode函数区别
代码如下 | 复制代码 |
$str='博 客'; echo urlencode($str); echo " "; echo rawurlencode($str); ?> |
url结果:
%B2%A9+%BF%CD
%B2%A9%20%BF%CD例子 2 :url中文编码方法
从url:"http://www.baidu.com/s?wd=博 客" 转为 url:http://www.baidu.com/s?wd=%E5%8D%9A%20%E5%AE%A2;
代码如下 | 复制代码 |
$url='http://www.baidu.com/s?wd=博 客'; |
结果:
http://www.baidu.com/s?wd=%E5%8D%9A%20%E5%AE%A2
或许用以下url编码函数
代码如下 | 复制代码 |
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); ?> |
url结果:
http://www.baidu.com/s?wd=%E5%8D%9A%20%E5%AE%A2

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
