PHP大写转小写重写优化?
我正在使用此 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;
}
I am using this PHP code to redirect any form of UPPERCASE in URI's to lowercase. There are three exceptions: if the URI includes either "adminpanel" or "search" there is no redirect, also if it already is lowercase there is no redirect
Do you see any way to improve the function in 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为在 URI 大小写混合的情况下,这将无法重定向。这是故意的吗?另外,使用 $trailed 和 strtolower($trailed) 的字符串比较是否比在第 4 行 if 语句的第三个子句中使用正则表达式更简洁?
I think this will fail to redirect in the case that a URI has mixed case. Is this intended? Also, might using string comparison of $trailed and strtolower($trailed) be less verbose than using a regular expression in the third clause of the if statement on line 4?
您可以让 preg_match() 测试字符串中是否存在大写字母,而不是比较原始字符串和 preg_replace() 的结果。
(这现在可能不相关,但作为旁注:pcre 有一些 unicode 支持。您可以使用 \p{Lu} 代替 [:upper:] 来测试 unicode 大写字母,请参阅 http://www.pcre.org/pcre.txt)
Instead of comparing the original string and the result of preg_replace() you could let preg_match() test, if there is an upper case letter in the string.
(This might not be relevant now but as a side note: pcre has some unicode support. Instead of [:upper:] you'd use \p{Lu} to test for unicode upper case letters, see http://www.pcre.org/pcre.txt)
采用组合方法,此代码比第一个代码快约 140%。只有一个 if 语句,里面有 strpos 和 preg_match 而不是字符串长度比较。
抱歉,我还没有声誉来投票选出最终版本的答案,非常感谢您的帮助:)
Taking a combined approach this code is about 140% faster than the first one. Only one if statement with the strpos inside and a preg_match instead of string length comparison.
Sorry I don't have the reputation yet to vote up the answers that lead to the final version and thank you very much for your help :)