http://domain.name/1-As Low As 10% Downpayment, Free Golf Membership!!!
以上网址将报告400 bad request
,
如何将此类标题转换为用户友好的良好请求?
答案 0 :(得分:22)
您可能想要使用“slug”。您不是使用逐字标题作为URL,而是strtolower()
并用连字符替换所有非字母数字字符,然后删除重复的连字符。如果你觉得额外的功劳,你也可以删除stopwords。
所以“1-低至10%首付,免费高尔夫会员!!!”变为:
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;
}
你可以用更长的正则表达式来缩短它,但它很简单。奖励是你可以使用相同的函数来验证查询参数,然后再在数据库上运行查询以匹配标题,这样有人就不会把愚蠢的东西粘在你的数据库中。
答案 1 :(得分:8)
请在此处查看第一个答案URL Friendly Username in PHP?:
function Slug($string)
{
return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
}
$user = 'Alix Axel';
echo Slug($user); // alix-axel
$user = 'Álix Ãxel';
echo Slug($user); // alix-axel
$user = 'Álix----_Ãxel!?!?';
echo Slug($user); // alix-axel
答案 2 :(得分:1)
你可以使用urlencode或rawurlencode ...例如维基百科那样做。看到这个链接: http://en.wikipedia.org/wiki/Ichigo_100%25
这是%=%25
的php编码答案 3 :(得分:0)
您可以使用rawurlencode()
功能
答案 4 :(得分:0)
我只是创建了一个有用的slug函数的要点:
https://gist.github.com/ninjagab/11244087
您可以使用它将标题转换为seo友好网址。
<?php
class SanitizeUrl {
public static function slug($string, $space="-") {
$string = utf8_encode($string);
if (function_exists('iconv')) {
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
}
$string = preg_replace("/[^a-zA-Z0-9 \-]/", "", $string);
$string = trim(preg_replace("/\\s+/", " ", $string));
$string = strtolower($string);
$string = str_replace(" ", $space, $string);
return $string;
}
}
$title = 'Thi is a test string with some "strange" chars ò à ù...';
echo SanitizeUrl::slug($title);
//this will output:
//thi-is-a-test-string-with-some-strange-chars-o-a-u
答案 5 :(得分:-1)
简化完整变量$change_to
和$to_change
<?php
// Just full the array list to make replacement complete
// In this space will change to _, à to just a
$to_change = [
' ', 'à', 'à', 'â','é', 'è', 'ê', 'ç', 'ù', 'ô', 'ö' // and so on
];
$change_to = [
'_', 'a', 'a', 'a', 'e', 'e', 'e','c', 'u', 'o', 'o' // and so on
];
$texts = 'This is my slug in êlàb élaboré par';
$page_id = str_replace($to_change, $change_to, $texts);