Reputation: 4432
Right now when users press a link in my php webapplications they are send to a page with url's like this: domain.com/faq/item/18483/
or domain.com/blog/item/37476
. But I want to add a title to these url so the user will have a clue what's behind the link (example: I share a link to a friend) like this: domain.com/faq/item/18483/I-have-a-question
.
If I have titles like this:
What is the best way to sanitize and convert them to this format:
Actually just like stackoverflow does with my title I want to create urls like this: http://stackoverflow.com/questions/22042539/how-to-generate-url-slugs-seo-urls-from-raw-input/
Upvotes: 0
Views: 726
Reputation: 15023
You could use a regular expression to change everything that isn't alphanumeric into a hyphen:
function slugify($string) {
// Make the whole string lowercase
$slug = strtolower($slug);
// Replace utf-8 characters with 7-bit ASCII equivelants
$slug = iconv("utf-8", "ascii//TRANSLIT", $input);
// Replace any number of non-alphanumeric characters with hyphens
$slug = preg_replace("/[^a-z0-9-]+/", "-", $string);
// Remove any hyphens from the beginning & end of the string
return trim($slug, "-");
}
The outputs for your sample strings are:
echo slugify("this is a faq item"); // this-is-a-faq-item
echo slugify("blog ®!@# message &hello&"); // blog-message-hello
Upvotes: 1