Created
May 3, 2023 12:55
-
-
Save sonichandni/3c83bf380809bf6bf61b9aa578ab35dc to your computer and use it in GitHub Desktop.
js and php create slug
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
// For php | |
public function createSlug($str) { | |
$str = trim($str); | |
$str = strtolower($str); | |
$from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;"; | |
$to = "aaaaeeeeiiiioooouuuunc------"; | |
$str = strtr($str, $from, $to); | |
$str = preg_replace('/[^a-z0-9 -]/', '', trim($str)); | |
$str = preg_replace('/\s+/', '-', trim($str)); | |
$str = preg_replace('/-+/', '-', trim($str)); | |
return trim($str); | |
} | |
// For javascript | |
function createSlug(str) { | |
str = str.trim().toLowerCase(); | |
const from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;"; | |
const to = "aaaaeeeeiiiioooouuuunc------"; | |
for (let i = 0, len = from.length; i < len; i++) { | |
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); | |
} | |
str = str.replace(/[^a-z0-9 -]/g, '').trim(); | |
str = str.replace(/\s+/g, '-'); | |
str = str.replace(/-+/g, '-').trim(); | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment