How do I sanitize title URIs with PHP?

对着背影说爱祢 提交于 2019-12-18 07:12:22

问题


I am programming a blog and I want the URIs to be the title like the question title here in stackoverflow or like wordpress.
What are the rules for sanitizing a URI?
Is there an already made code in PHP that does this?

Thanks in advance,
Omer


回答1:


Many CMS's have implemented something like that, the one of Wordpress has been posted in another question. You might be interested in the question about this technique in general, too.




回答2:


This might be the shortest way to replace any non alphanumeric character with a single hyphen:

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



回答3:


Here's how drupal does it.

In case of site goes down:

<?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:


Generally you'll want your URL to have only 0-9 and a-z, and make sure that everything is lowercase. Replace spaces with dashes (-), and strip the rest of the gibberish.

SO pretty much has it figured out.



来源:https://stackoverflow.com/questions/1432463/how-do-i-sanitize-title-uris-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!