How can I create a SEO friendly dash-delimited url from a string?
C#
public string toFriendly(string subject)
{
subject = subject.Trim().ToLower();
subject = Regex.Replace(subject, @"\s+", "-");
subject = Regex.Replace(subject, @"[^A-Za-z0-9_-]", "");
return subject;
}
Here is my solution in C#
private string ToSeoFriendly(string title, int maxLength) {
var match = Regex.Match(title.ToLower(), "[\\w]+");
StringBuilder result = new StringBuilder("");
bool maxLengthHit = false;
while (match.Success && !maxLengthHit) {
if (result.Length + match.Value.Length <= maxLength) {
result.Append(match.Value + "-");
} else {
maxLengthHit = true;
// Handle a situation where there is only one word and it is greater than the max length.
if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
}
match = match.NextMatch();
}
// Remove trailing '-'
if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
return result.ToString();
}
I would follow these steps:
- convert string to lower case
- replace unwanted characters by hyphens
replace multiple hyphens by one hyphen(not necessary as thepreg_replace()
function call already prevents multiple hyphens)- remove hypens at the begin and end if necessary
- trim if needed from the last hyphen before position x to the end
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;
}
Here's a solution for php:
function make_uri($input, $max_length) {
if (function_exists('iconv')) {
$input = @iconv('UTF-8', 'ASCII//TRANSLIT', $input);
}
$lower = strtolower($input);
$without_special = preg_replace_all('/[^a-z0-9 ]/', '', $input);
$tokens = preg_split('/ +/', $without_special);
$result = '';
for ($tokens as $token) {
if (strlen($result.'-'.$token) > $max_length+1) {
break;
}
$result .= '-'.$token;
}
return substr($result, 1);
}
usage:
echo make_uri('In C#: How do I add "Quotes" around string in a ...', 500);
Unless you need the uris to be typable, they don't need to be small. But you should specify a maximum so that the urls work well with proxies etc.