Skip to content

Instantly share code, notes, and snippets.

@sonichandni
Created May 3, 2023 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonichandni/3c83bf380809bf6bf61b9aa578ab35dc to your computer and use it in GitHub Desktop.
Save sonichandni/3c83bf380809bf6bf61b9aa578ab35dc to your computer and use it in GitHub Desktop.
js and php create slug
// 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