代码之家  ›  专栏  ›  技术社区  ›  the_drow

如何用PHP清理标题URI?

  •  2
  • the_drow  · 技术社区  · 15 年前

    我正在编写一个博客,我希望uris是标题,比如stackoverflow中的问题标题或者wordpress。
    清理URI的规则是什么?
    是否有一个已经在PHP中生成的代码可以做到这一点?

    事先谢谢,
    奥马尔

    4 回复  |  直到 9 年前
        1
  •  2
  •   Community CDub    7 年前

    许多CMS已经实现了类似的功能, the one of Wordpress 已在中发布 another question . 您可能对 question about this technique 一般来说,也是。

        2
  •  6
  •   Gumbo    15 年前

    这可能是用单个连字符替换任何非字母数字字符的最短方法:

    trim(preg_replace('/[^a-z0-9-]+/', '-', strtolower($str)), '-')
    
        3
  •  6
  •   raspi    11 年前

    Here's how drupal does it .

    如果现场出现故障:

    <?php
    function pathauto_cleanstring($string)
    {
        $url = $string;
        $url = preg_replace('~[^\\pL0-9_]+~u', '-', $url); // substitutes anything but letters, numbers and '_' with separator
        $url = trim($url, "-");
        $url = iconv("utf-8", "us-ascii//TRANSLIT", $url); // TRANSLIT does the whole job
        $url = strtolower($url);
        $url = preg_replace('~[^-a-z0-9_]+~', '', $url); // keep only letters, numbers, '_' and separator
        return $url;
    }
    
        4
  •  2
  •   Will Morgan    15 年前

    一般来说,您希望您的URL只有0-9和a-z,并确保所有内容都是小写的。用破折号(-)替换空格,去掉其余的乱码。

    这件事已经解决了。