PHP uppercase to lowercase rewrite optimization?
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 redirec开发者_如何学Ct, 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;
}
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?
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.
if ( preg_match('/[[:upper:]]/', $_SERVER['REQUEST_URI']) ) {
if ( false===stripos($trailed, 'adminpanel') && false===stripos($trailed, 'search') {
// strotolower
// ...
}
}
(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)
$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;
}
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 :)
精彩评论