4

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

使用 slug 而不是 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中有?.时,则无法显示!

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

4

2 回答 2

8

当您有这样的 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 的情况下显示带有破折号的 URL slug 时出现问题:您会看到您的问题加载得很好;-)

于 2010-04-15T18:05:51.653 回答
0

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

于 2010-04-15T18:13:02.540 回答