【问题标题】:How can I check the post slug?我如何检查post slug?
【发布时间】: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); 

【问题讨论】:

    标签: php regex url


    【解决方案1】:

    好的,简单来说,有一个好的url和一个请求的url

    如果请求的 url 不等于好的 url

    将访问者重定向到好人

    <?
    $id = '38839016';
    $good_url = '/questions/'.$id.'/'.str_replace("-"," ",strtolower($result['title']));
    
    preg_match( '/\/[0-9]+\/([a-z0-9-]+)\/.*/', $_SERVER[REQUEST_URI], $matches);
    if ($matches[1] != str_replace("-"," ",strtolower($result['title'])))
    header('Location: '.$good_url);
    

    【讨论】:

    • 如果有一些作为 GET 方法传递的参数,此解决方案将失败,如下所示:?arg1=value1&amp;arg2=value2
    • @MartinAJ 抱歉,我添加了这个答案,因为您添加了 stackoverflow 示例
    • 您是否只想更正 url 中的 slug 而不修改 url 中的任何其他语法?
    • 好的,我正在搜索解决方案
    • 检查当前的答案,它可能会更有帮助
    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 2014-02-22
    • 2018-09-13
    • 2023-03-20
    • 2020-10-02
    • 2012-01-08
    • 2016-10-31
    • 2020-01-07
    相关资源
    最近更新 更多