url 编码和 str_replace

url encode and str_replace

我正在尝试对网站进行编码,并使用当前的 RFC 3986 标准并使用此功能:

function getUrl() {

      $url  = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
      $url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
      $url .= $_SERVER["REQUEST_URI"];

      $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
      $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");

      return str_replace($entities, $replacements, urlencode($url));

    }

URL 添加: http://localhost/test/test-countdown/?city=hayden&eventdate=20160301 Returns: http://localhost/test/test-countdown/?city=hayden&eventdate=20160301 未编码用 //& 替换

如果您想要以这种格式对 URL(不是站点)进行编码:

http%3A%2F%2Flocalhost%2Ftest%2Ftest-countdown%2F%3Fcity%3Dhayden%26eventdate%3D20160301

使用内置 php 函数 rawurlencode( $url )

虽然规范的解决方案是像 fusion3k 所说的那样简单地使用 rawurlencode(),但值得注意的是,在推出自己的解决方案时,您应该:

  1. 仔细聆听规范并对 所有 个既不是字母数字也不是 -_.~.
  2. 之一的字符进行编码
  3. 更懒惰,拒绝输入所有这些实体。我的经验是,如果没有非常好的理由,我不会键入超过 10 个数组条目。自动化!

代码:

function encode($str) {
    return preg_replace_callback(
        '/[^\w\-_.~]/',
        function($a){ return sprintf("%%%02x", ord($a[0])); },
        $str
    );
}

var_dump(encode('http://localhost/test/test-countdown/?city=hayden&eventdate=20160301'));

结果:

string(88) "http%3a%2f%2flocalhost%2ftest%2ftest-countdown%2f%3fcity%3dhayden%26eventdate%3d20160301"

其他人提到了 rawurlencode(),但您的代码的问题是您的数组倒置了。

像这样切换数组:

function getUrl() {

  $url  = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
  $url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
  $url .= $_SERVER["REQUEST_URI"];

  $entities = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");      
  $replacements = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');

  return str_replace($entities, $replacements, urlencode($url));
}