Created
November 5, 2023 10:37
-
-
Save muath-ye/17bc0b79ff690840a504e45b4155d390 to your computer and use it in GitHub Desktop.
This function works like \Str::slug of Laravel with support for Arabic strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generates a slug for URL from a given title. | |
* | |
* @param string $title The title to convert to a slug. | |
* @param string $separator The separator to use in the slug. Default is '-'. | |
* @param string|null $language The language to use for ASCII conversion. Default is null. | |
* @param array $dictionary An array of dictionary words to replace in the slug. Default is ['@' => 'at']. | |
* @return string The generated slug. | |
*/ | |
function slug($title, $separator = '-', $language = null, $dictionary = ['@' => 'at']) { | |
if (is_null($title)) { | |
return ""; | |
} | |
if (!is_null($language)) { | |
// The peace of code below uses Laravel \Illuminate\Support\Str class | |
$title = $language ? \Str::ascii($title, $language) : $title; | |
} | |
// Strip whitespace (or other characters) from the beginning and end of a string | |
$title = trim($title); | |
// Make a string lowercase | |
$title = mb_strtolower($title, "UTF-8");; | |
// Replace dictionary words | |
foreach ($dictionary as $key => $value) { | |
$dictionary[$key] = $separator.$value.$separator; | |
} | |
$title = str_replace(array_keys($dictionary), array_values($dictionary), $title); | |
// Remove all characters that are not the separator, letters, numbers, or whitespace | |
$title = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $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)); | |
// Replace all separator characters and whitespace by a single separator | |
$title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title); | |
return $title; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment