【发布时间】:2016-08-09 00:03:46
【问题描述】:
场景: 如您所知,StackOverflow 会检查问题中的标题。我的意思是当你打开这个 URL 时:
http://stackoverflow.com/questions/38839016/should-i-store-the-result-of-an-function
它会自动替换为:
http://stackoverflow.com/questions/38839016/should-i-store-the-result-of-an-function-into-an-array
该替换是因为第一个 URL 不完整。
好吧,我正在尝试用 PHP 制作这样的系统。这是我的尝试:
// getting this from the URL
$id = '38839016';
// fetching this from database based on that id (38839016)
$real_title = $result['title'];
//=> Should I store the result of an function into an array
$real_title = str_replace("-"," ",strtolower($real_title));
//=> should-i-store-the-result-of-an-function-into-an-array
// getting whole uri
$current_uri = $_SERVER["REQUEST_URI"];
//=> /questions/38839016/should-i-store-the-result-of-an-function
我想要做什么:我需要将$real_title 与$current_uri 的标题部分进行比较。如何确定“title-part”?它是在$id.'/' 之后直到/ 或? 或$ (字符串结尾) 的所有内容。我该如何进行比较?
然后:
if ( preg_match("//", $current_uri) ) {
// all fine. continue loading the page
continue;
} else {
// replace title-part of the $current_uri with $real_title
preg_replace("//", $real_title, $current_uri);
// redirect to this post with correct slug
header('Location: '.$_SERVER["HTTP_HOST"].);
}
简单地说,我想完成这些:
if ( preg_match("//", $current_uri) ) {
preg_replace("//", $real_title, $current_uri);
【问题讨论】: