PHP-Function: Create slugs from string

Every website needs to implement readable URLs for internal linking. When you are using a blogging tool like WordPress or a CMS like Typo3, you automatically get the URL slug generator built in.

But sometimes, you are developing your own software and are in need of a function that simply generates a slug for you.

Search no more, because here it is: the PHP function to generate slugs for you.

function slugify($input, $word_delimiter='-') {
	$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $input);
	$slug = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $slug);
	$slug = strtolower(trim($slug, '-'));
	$slug = preg_replace("/[\/_|+ -]+/", $word_delimiter, $slug);
	return $slug;
}

$slugString = slugify("This is just a small test for a slug creation");
echo $slugString;
// returns : this-is-just-a-small-test-for-a-slug-creation

This PHP function takes a simple string as first parameter, which will be turned into your slug. In this example, we are using the string This is just a small test for a slug creation .

The function slugify  then returns a nice, readable slug for you.

this-is-just-a-small-test-for-a-slug-creation

If you want to use another delimiter, simply pass it as the second parameter to the function.

3 Antworten auf „PHP-Function: Create slugs from string“

  1. Ein Vorschlag für deutsche Strings:

    function slugify($input, $word_delimiter=‘-‚) {
    $replaceSet = [‚ä‘ => ‚ae‘, ‚ö‘ => ‚oe‘, ‚ü‘ => ‚ue‘, ‚ß‘ => ’ss‘, ‚ ‚ => ‚-‚];

    $slug = strtr($input, $replaceSet);
    $slug = iconv(‚UTF-8‘, ‚ASCII//TRANSLIT‘, $slug);
    $slug = preg_replace(„/[^a-zA-Z0-9\/_|+ -]/“, “, $slug);
    $slug = strtolower(trim($slug, ‚-‚));
    $slug = preg_replace(„/[\/_|+ -]+/“, $word_delimiter, $slug);
    $slug = substr($slug, 0, 95);

    return $slug;
    }

    :)

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.