如何使用PHP清理标题URI?

时间:2009-09-16 11:43:03

标签: php rest uri sanitization

我正在编写一个博客,我希望URI在stackoverflow中像问题标题一样成为标题,或者像wordpress一样。
清理URI有哪些规则?
在PHP中是否有已经制作的代码可以做到这一点?

提前致谢,
奥马尔

4 个答案:

答案 0 :(得分:6)

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

trim(preg_replace('/[^a-z0-9-]+/', '-', strtolower($str)), '-')

答案 1 :(得分:6)

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

答案 2 :(得分:2)

许多CMS都实现了类似的功能,the one of Wordpress已在another question中发布。您也可能对question about this technique感兴趣。

答案 3 :(得分:2)

通常,您希望您的网址只有0-9和a-z,并确保所有内容都是小写的。用破折号( - )替换空格,并剥去其余的乱码。

几乎已经弄清楚了。