Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add full UTF8 support to the Str::slug method #6867

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/Illuminate/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,26 +254,41 @@ public static function singular($value)
*
* @param string $title
* @param string $separator
* @param bool $utf8
* @return string
*/
public static function slug($title, $separator = '-')
public static function slug($title, $separator = '-', $utf8 = false)
{
$title = static::ascii($title);
$title = $utf8 ? $title : static::ascii($title);

// Convert all dashes/underscores into separator
$flip = $separator == '-' ? '_' : '-';

$title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);

$title = $utf8 ? strtolower($title) : mb_strtolower($title);

// Remove all characters that are not the separator, letters, numbers, or whitespace.
$title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($title));
$title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', $title);

// Replace all separator characters and whitespace by a single separator
$title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);

return trim($title, $separator);
}

/**
* Generate a utf8-compatible URL friendly "slug" from a given string.
*
* @param string $title
* @param string $separator
* @return string
*/
public static function lightSlug($title, $separator = '-')
{
return static::slug($title, $separator, true);
}

/**
* Convert a string to snake case.
*
Expand Down
4 changes: 4 additions & 0 deletions tests/Support/SupportStrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ public function testSlug()
$this->assertEquals('hello-world', Str::slug('hello-world'));
$this->assertEquals('hello-world', Str::slug('hello_world'));
$this->assertEquals('hello_world', Str::slug('hello_world', '_'));
$this->assertEquals('سلام-دنیا', Str::slug('سلام دنیا', '-', true));
$this->assertEquals('سلام-دنیا', Str::slug('سلام-دنیا', '-', true));
$this->assertEquals('سلام_دنیا', Str::slug('سلام_دنیا', '_', true));
$this->assertEquals('سلام-دنیا', Str::slug('سلام_دنیا', '-', true));
}


Expand Down