在PHP中将标题转换为url兼容模式的最佳方法? [英] Best way to convert title into url compatible mode in PHP?
问题描述
http://domain.name/1-As Low As 10% Downpayment, Free Golf Membership!!!
上面的网址将报告400 bad request
,
如何将此类标题转换为用户友好的好请求?
how to convert such title to user friendly good request?
推荐答案
您可能想改用"slug".而不是使用逐字标题作为URL,您 strtolower()
并用连字符替换所有非字母数字字符,然后删除重复的连字符.如果您想获得额外的荣誉,可以删除停用词也是如此.
You may want to use a "slug" instead. Rather than using the verbatim title as the URL, you strtolower()
and replace all non-alphanumeric characters with hyphens, then remove duplicate hyphens. If you feel like extra credit, you can strip out stopwords, too.
因此,首付低至10%,免费的高尔夫会员资格!!!"变成:
So "1-As Low As 10% Downpayment, Free Golf Membership!!!" becomes:
as-low-as-10-downpayment-free-gold-membership
类似这样的东西:
function sluggify($url)
{
# Prep string with some basic normalization
$url = strtolower($url);
$url = strip_tags($url);
$url = stripslashes($url);
$url = html_entity_decode($url);
# Remove quotes (can't, etc.)
$url = str_replace('\'', '', $url);
# Replace non-alpha numeric with hyphens
$match = '/[^a-z0-9]+/';
$replace = '-';
$url = preg_replace($match, $replace, $url);
$url = trim($url, '-');
return $url;
}
您可以使用更长的正则表达式来缩短它,但是它非常简单.好处是,您可以在数据库上运行查询以匹配标题之前,使用相同的函数来验证查询参数,从而使某人无法将愚蠢的东西粘贴到数据库中.
You could probably shorten it with longer regexps but it's pretty straightforward as-is. The bonus is that you can use the same function to validate the query parameter before you run a query on the database to match the title, so someone can't stick silly things into your database.
这篇关于在PHP中将标题转换为url兼容模式的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!