根据要执行的RFC标准编码类型,或者如果需要自定义编码,可能要创建自己的类。
/**
* UrlEncoder make it easy to encode your URL
*/
class UrlEncoder{
public const STANDARD_RFC1738 = 1;
public const STANDARD_RFC3986 = 2;
public const STANDARD_CUSTOM_RFC3986_ISH = 3;
// add more here
static function encode($string, $rfc){
switch ($rfc) {
case self::STANDARD_RFC1738:
return urlencode($string);
break;
case self::STANDARD_RFC3986:
return rawurlencode($string);
break;
case self::STANDARD_CUSTOM_RFC3986_ISH:
// Add your custom encoding
$entities = ['%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'];
$replacements = ['!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]"];
return str_replace($entities, $replacements, urlencode($string));
break;
default:
throw new Exception("Invalid RFC encoder - See class const for reference");
break;
}
}
}
使用示例:
$dataString = "https://www.google.pl/search?q=PHP is **great**!&id=123&css=#kolo&email=me@liszka.com)";
$dataStringUrlEncodedRFC1738 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC1738);
$dataStringUrlEncodedRFC3986 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC3986);
$dataStringUrlEncodedCutom = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_CUSTOM_RFC3986_ISH);
将输出:
string(126) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP+is+%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(130) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP%20is%20%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(86) "https://www.google.pl/search?q=PHP+is+**great**!&id=123&css=#kolo&email=me@liszka.com)"
*了解有关RFC标准的更多信息:https :
//datatracker.ietf.org/doc/rfc3986/
以及urlencode和rawurlencode?
foo bar
,输入文本字段,foo+bar
在URL中创建)。