【问题标题】:Problem in displaying a URL slug with dash用破折号显示 URL slug 时出现问题
【发布时间】:2011-02-08 12:28:52
【问题描述】:

我用破折号为我的故事 URL 做了一个 slug,例如:

Fetching records with slug instead of ID

这是我创建 slug 的代码:

function Slugit($title) {
    $title = strip_tags($title);
    // Preserve escaped octets.
    $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
    // Remove percent signs that are not part of an octet.
    $title = str_replace('%', '', $title);
    // Restore octets.
    $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);


    $title = remove_accents($title);
    if (seems_utf8($title)) {
        if (function_exists('mb_strtolower')) {
            $title = mb_strtolower($title, 'UTF-8');
        }
        $title = utf8_uri_encode($title, 500);
    }

    $title = strtolower($title);
    $title = preg_replace('/&.+?;/', '', $title); // kill entities
    $title = str_replace('.', '-', $title);
    $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
    $title = preg_replace('/\s+/', '-', $title);
    $title = preg_replace('|-+|', '-', $title);
    $title = trim($title, '-');


    return $title;
}

你可以看到破折号,到这里,一切都很好。但是当我点击链接时,它无法打开并找到我的数据库,因为它是正常保存的,没有破折号。

所以我写了一些东西来删除破折号:

$string = str_replace('-', ' ', $string);

但是当URL中有?.时,就不能显示了!

有什么帮助找回原来的 URL 吗?!

【问题讨论】:

标签: php url slug


【解决方案1】:

当您有这样的 URL 时:

https://stackoverflow.com/questions/2647789/problem-in-displaying-a-slug-with-dash

problem-in-displaying-a-slug-with-dash 部分不是很重要:它只是很好:

  • 显示
  • 供用户阅读,看看问题是关于什么的
  • 用于搜索引擎,作为一种 SEO 机制。


真正重要的是,在那个 URL 中,2647789 部分:它是数据库中问题的标识符 -- 即,它是用于加载问题的 URL 部分。

这意味着无需将 slug 转换为用户首次键入的内容:唯一重要的是您在每个 URL 中传递数据的标识符,并使用它来查找您的数据。


而且,如果您想要某种证明:尝试在没有 slug 的情况下转到 Problem in displaying a URL slug with dash:您会发现您的问题加载得很好;-)

【讨论】:

  • 不仅不重要,还被忽略了!你可以查看http://stackoverflow.com/questions/2647789/this-is-NOT-the-title就好了! :)
  • 问题在这里我没有使用标识符:所以你说没有办法找到原始网址?因为wordpress正在这样做,但我不知道怎么做!?
  • @Mac :如果您真的不想存储标识符,则可以使用“干净” URL 作为标识符:将“干净” URL 作为附加字段存储在数据库中,并且使用该字段取回您的数据。
  • 谢谢,还有一个问题,为什么这个网站没有在 url 的末尾使用斜杠,但 wordpress 这样做,这很重要吗?
  • 不客气 :-) ;;;不,我认为最终的 / 一点也不重要——好吧,也许 wordpress 期望它,但是,在这种情况下,这是 wordpress 团队做出的选择,而不是某种标准。
【解决方案2】:

如果您没有数字 ID,并且仅使用 slug 来识别数据库中的记录。然后,您也可以简单地将 slug 也存储在数据库中并使用该 slug 进行查询。

【讨论】:

    猜你喜欢
    • 2010-10-06
    • 2011-05-30
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 2021-12-18
    • 2014-04-08
    • 2011-08-25
    • 2022-11-22
    相关资源
    最近更新 更多