【问题标题】:PHP uppercase to lowercase rewrite optimization?PHP大写到小写重写优化?
【发布时间】:2010-12-24 03:44:46
【问题描述】:

我正在使用此 PHP 代码将 URI 中任何形式的大写字母重定向为小写字母。有三个例外:如果 URI 包含“adminpanel”或“search”,则没有重定向,如果它已经是小写,则没有重定向

你有什么方法可以改进 PHP 中的功能吗?

$trailed = $_SERVER['REQUEST_URI'];
$pos1 = strpos($trailed,"adminpanel");
$pos2 = strpos($trailed,"search");
if ($pos1 === false && $pos2 === false && strlen($trailed) !== strlen(preg_replace('/[A-Z]/', '',     $trailed))) {
    $trailed = strtolower($trailed);
    header('HTTP/1.1 301 Moved Permanently'); 
    header('Location: http://'. $_SERVER["SERVER_NAME"] . $trailed);
    exit;
}

【问题讨论】:

  • 如果你在 Apache 上运行,我会使用 Mod_Rewrite,而不是 PHP:chrisabernethy.com/force-lower-case-urls-with-mod_rewrite(你需要调整 RewriteCond 模式以排除“adminpanel”和“search”。)
  • 我很乐意,但现在不能进入 httpd.conf :(
  • 500 错误代码:RewriteEngine On RewriteMap lc int:tolower RewriteCond %{REQUEST_URI} [AZ] RewriteRule (.*) ${lc:$1} [R=301,L]
  • 我不是 Mod_Rewrite 大师,否则我会发布答案,而不是评论。尽管如此,该链接上的 cmets 表明 RewriteMap 仅适用于 httpd.conf,而不适用于 .htaccess。不过,网上有很多关于这个主题的文章,所以如果你在 Google 周围搜索一下,你可能会找到另一个解决方案。
  • 谢谢乔丹,:) 我花了大约 20 分钟的谷歌搜索,只找到了几次上述解决方案或类似的解决方案。由于我无权访问 httpd.conf,因此我将代码保存在我的 sn-ps 库中以备将来使用,但这就是我现在所能做的:(。

标签: php redirect uppercase lowercase


【解决方案1】:
$trailed = $_SERVER['REQUEST_URI'];
if (!strpos($trailed,"admin") && !strpos($trailed,"search") && preg_match('/[[:upper:]]/', $trailed)) {
  $trailed = strtolower($trailed);
  header('HTTP/1.1 301 Moved Permanently'); 
  header('Location: http://'. $_SERVER["SERVER_NAME"] . $trailed);
  exit;
}

采用组合方法,此代码比第一个快 140%。只有一个 if 语句,其中包含 strpos 和 preg_match 而不是字符串长度比较。

抱歉,我还没有声望对最终版本的答案进行投票,非常感谢您的帮助 :)

【讨论】:

    【解决方案2】:

    如果字符串中有大写字母,您可以让 preg_match() 测试,而不是比较原始字符串和 preg_replace() 的结果。

    if ( preg_match('/[[:upper:]]/', $_SERVER['REQUEST_URI']) ) {
      if ( false===stripos($trailed, 'adminpanel') && false===stripos($trailed, 'search') {
        // strotolower
        // ...
      }
    }
    

    (现在这可能无关紧要,但作为旁注:pcre 有一些 unicode 支持。您可以使用 \p{Lu} 而不是 [:upper:] 来测试 unicode 大写字母,请参阅http://www.pcre.org/pcre.txt )

    【讨论】:

      【解决方案3】:

      我认为如果 URI 大小写混合,这将无法重定向。这是故意的吗?此外,使用 $trailed 和 strtolower($trailed) 的字符串比较是否比在第 4 行的 if 语句的第三个子句中使用正则表达式更简洁?

      【讨论】:

      • 它将重定向各种混合大小写。就正则表达式而言,它比字符串比较快得多:)
      猜你喜欢
      • 2020-01-27
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多