Skip to content

Instantly share code, notes, and snippets.

@garcon
Last active April 13, 2022 10:48
Show Gist options
  • Save garcon/fd50d7ea81df93b67540134547789880 to your computer and use it in GitHub Desktop.
Save garcon/fd50d7ea81df93b67540134547789880 to your computer and use it in GitHub Desktop.
Change any string into SEO friendly URL slug
<?php
// example code
setlocale(LC_CTYPE, 'cs_CZ');
$str = "Běloučký kůň úpěl ďábelské ódy $ ' 1234";
print
preg_replace('/(?<=-)-+/', '', // Replace all duplicase hyphens with one only
preg_replace( '/[^-a-z0-9]/', '', // Strip all non-alfanumeric characters or hyphens
strtr( // Replace spaces with hyphens
strtolower( // Transform to lowercase
iconv('UTF-8', 'ASCII//TRANSLIT', $str) // Transliterate to ASCII
),
[" " => "-"]
)
)
)
;
// Expected output:
// beloucky-kun-upel-dabelske-ody-1234
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment