Convert String into Slug With Single-Hyphen Delimiters Only

Convert string into slug with single-hyphen delimiters only


function slug($z){
$z = strtolower($z);
$z = preg_replace('/[^a-z0-9 -]+/', '', $z);
$z = str_replace(' ', '-', $z);
return trim($z, '-');
}

How to convert a Title to a URL slug in jQuery?

I have no idea where the 'slug' term came from, but here we go:

function convertToSlug(Text) {
return Text.toLowerCase()
.replace(/ /g, '-')
.replace(/[^\w-]+/g, '');
}

The first replace method will change spaces to hyphens, second, replace removes anything not alphanumeric, underscore, or hyphen.

If you don't want things "like - this" turning into "like---this" then you can instead use this one:

function convertToSlug(Text) {
return Text.toLowerCase()
.replace(/[^\w ]+/g, '')
.replace(/ +/g, '-');
}

That will remove hyphens (but no spaces) on the first replace, and in the second replace it will condense consecutive spaces into a single hyphen.

So "like - this" comes out as "like-this".

Creating slug with strtolower() and preg_replace()

You are already pretty close:

  • You put the ID to the beginning of the intersting part. That allows you to query your database by the ID which is unique and fast.
  • You have the understanding that you need to transform the text of the headline into the slug variant of it and you already know that this is string processing.

You have some steps left to finish this. Somme notes:

  • Create yourself a function that does the string transformation. The important part here is, that you can call it simply.
  • When the request to an article comes in, fetch the article based on the ID value you obtain from the string: $assigned = sscanf($slug, '%d-', $id);
  • For SEO, do the same as when creating the link. Then compare if the current link still is correct (the headline might have changed). If not, do a permanent redirect to the correct link.

And that's it!

Ruby post title to slug


slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')

downcase makes it lowercase. The strip makes sure there is no leading or trailing whitespace. The first gsub replaces spaces with hyphens. The second gsub removes all non-alpha non-dash non-underscore characters (note that this set is very close to \W but includes the dash as well, which is why it's spelled out here).

PHP function to make slug (URL string)

Instead of a lengthy replace, try this one:

public static function slugify($text, string $divider = '-')
{
// replace non letter or digits by divider
$text = preg_replace('~[^\pL\d]+~u', $divider, $text);

// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);

// trim
$text = trim($text, $divider);

// remove duplicate divider
$text = preg_replace('~-+~', $divider, $text);

// lowercase
$text = strtolower($text);

if (empty($text)) {
return 'n-a';
}

return $text;
}

This was based off the one in Symfony's Jobeet tutorial.

URL Slugify algorithm in C#?

http://predicatet.blogspot.com/2009/04/improved-c-slug-generator-or-how-to.html

public static string GenerateSlug(this string phrase) 
{
string str = phrase.RemoveAccent().ToLower();
// invalid chars
str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
// convert multiple spaces into one space
str = Regex.Replace(str, @"\s+", " ").Trim();
// cut and trim
str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim();
str = Regex.Replace(str, @"\s", "-"); // hyphens
return str;
}

public static string RemoveAccent(this string txt)
{
byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt);
return System.Text.Encoding.ASCII.GetString(bytes);
}

Remove all special characters from a string

This should do what you're looking for:

function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

Usage:

echo clean('a|"bc!@£de^&$f g');

Will output: abcdef-g

Edit:

Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?

function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

How to replace one or more consecutive spaces with one single character?

You can use preg_replace to replace any sequence of whitespace chars with a dash...

 $string = preg_replace('/\s+/', '-', $string);
  • The outer slashes are delimiters for the pattern - they just mark where the pattern starts and ends
  • \s matches any whitespace character
  • + causes the previous element to match 1 or more times. By default, this is 'greedy' so it will eat up as many consecutive matches as it can.
  • See the manual page on PCRE syntax for more details


Related Topics



Leave a reply



Submit