使用短划线显示URL slug时出现问题

时间:2010-04-15 18:00:27

标签: php url slug

我用破折号为我的故事网址制作了一个slu :::

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);

但是,如果网址中有?.,则无法显示!

有关检索原始网址的任何帮助吗?!

2 个答案:

答案 0 :(得分:8)

如果您有这样的网址:

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

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

  • 显示
  • 供用户阅读,并查看有关的问题
  • 用于搜索引擎,作为SEO机制。


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

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


并且,如果你想要某种证据:试着去Problem in displaying a URL slug with dash没有slu ::你会看到你的问题加载得很好; - )

答案 1 :(得分:0)

如果您没有数字ID并且仅使用slug来标识数据库中的记录。然后你可以简单地将slug存储在数据库中并用那个slug查询它。

相关问题