Take a string such as:
In C#: How do I add \"Quotes\" around string in a comma delimited list of strings?
and convert it to:
I would follow these steps:
preg_replace()
function call already prevents multiple hyphens)So, all together in a function (PHP):
function generateUrlSlug($string, $maxlen=0)
{
$string = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');
if ($maxlen && strlen($string) > $maxlen) {
$string = substr($string, 0, $maxlen);
$pos = strrpos($string, '-');
if ($pos > 0) {
$string = substr($string, 0, $pos);
}
}
return $string;
}
This is close to how Stack Overflow generates slugs:
public static string GenerateSlug(string title)
{
string slug = title.ToLower();
if (slug.Length > 81)
slug = slug.Substring(0, 81);
slug = Regex.Replace(slug, @"[^a-z0-9\-_\./\\ ]+", "");
slug = Regex.Replace(slug, @"[^a-z0-9]+", "-");
if (slug[slug.Length - 1] == '-')
slug = slug.Remove(slug.Length - 1, 1);
return slug;
}
In python, (if django is installed, even if you are using another framework.)
from django.template.defaultfilters import slugify
slugify("In C#: How do I add "Quotes" around string in a comma delimited list of strings?")
Solution in shell:
echo 'In C#: How do I add "Quotes" around string in a comma delimited list of strings?' | \
tr A-Z a-z | \
sed 's/[^a-z0-9]\+/-/g;s/^\(.\{1,20\}\).*/\1/'
A slightly cleaner way of doing this in PHP at least is:
function CleanForUrl($urlPart, $maxLength = null) {
$url = strtolower(preg_replace(array('/[^a-z0-9\- ]/i', '/[ \-]+/'), array('', '-'), trim($urlPart)));
if ($maxLength) $url = substr($url, 0, $maxLength);
return $url;
}
Might as well do the trim()
at the start so there is less to process later and the full replacement is done with in the preg_replace()
.
Thxs to cg for coming up with most of this: What is the best way to clean a string for placement in a URL, like the question name on SO?
A better version:
function Slugify($string)
{
return strtolower(trim(preg_replace(array('~[^0-9a-z]~i', '~-+~'), '-', $string), '-'));
}