改进将字符串转换为可读 url [英] Improve converting string to readable urls
本文介绍了改进将字符串转换为可读 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下函数重写包含各种字符的新闻和产品标题的 url.我希望创建的字符串仅由字母数字值和-"组成,但没有结尾-"或空格,也没有重复的-".下面的函数工作正常,但我想知道有没有什么方法可以写得更简单或更高效?
The following function rewrites urls from news and product titles that contain all sorts of characters. The string I wish to create consists of only alphanumeric values and "-", but no ending "-" or whitespace and no repeated "-". The below function works fine, but I wondered if there is any way to write it simpler or more efficient?
function urlName($string) {
$string = trim($string); // no open ends
$string = strtolower($string); // all lowercase
$string = strtr($string, 'äöåÄÖÅ', 'aoaaoa'); // substitute umlauts
$string = preg_replace('/[\W]+/', '-', $string); // substitute non-word characters with -
$string = preg_replace('/^-*|-*$/', '', $string); // no beinging or ending -
return $string;
}
推荐答案
我认为你的代码可以压缩成这样:
I think your code can be compacted to this:
function urlName($string) {
$patterns = array('/^[\s-]+|[\s-]+$/', '/[\W]+/');
$replacements = array('', '-');
$string = strtr(strtolower($string), 'äöåÄÖÅ', 'aoaaoa');
// or you can use:
// $string = strtr(strtolower($string), $someTrMapping);
return preg_replace($patterns, $replacements, $string);
}
这篇关于改进将字符串转换为可读 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文