The OP is not explicitly describing all of the attributes of a slug, but this is what I am gathering from the intent.
My interpretation of a perfect, valid, condensed slug aligns with this post: https://wordpress.stackexchange.com/questions/149191/slug-formatting-acceptable-characters#:~:text=However%2C%20we%20can%20summarise%20the,or%20end%20with%20a%20hyphen.
I find none of the earlier posted answers to achieve this consistently (and I'm not even stretching the scope of the question to include multi-byte characters).
- convert all characters to lowercase
- replace all sequences of one or more non-alphanumeric characters to a single hyphen.
- trim the leading and trailing hyphens from the string.
I recommend the following one-liner which doesn't bother declaring single-use variables:
return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');
Not shown in my demo link, here is an attempt to better handle multibyte strings, though it doesn't quite accommodate as many scenarios as Casimir's answer.
return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower(iconv('utf-8', 'ascii//translit', $string))), '-');
I have also prepared a demonstration which highlights what I consider to be inaccuracies in the other answers. (Demo)
'This, is - - the URL!' input 'this-is-the-url' expected 'this-is-----the-url' SilentGhost 'this-is-the-url' mario 'This-is---the-URL' Rooneyl 'This-is-the-URL' AbhishekGoel 'This, is - - the URL!' HelloHack 'This, is - - the URL!' DenisMatafonov 'This,-is-----the-URL!' AdeelRazaAzeemi 'this-is-the-url' mickmackusa --- 'Mork & Mindy' input 'mork-mindy' expected 'mork--mindy' SilentGhost 'mork-mindy' mario 'Mork--Mindy' Rooneyl 'Mork-Mindy' AbhishekGoel 'Mork & Mindy' HelloHack 'Mork & Mindy' DenisMatafonov 'Mork-&-Mindy' AdeelRazaAzeemi 'mork-mindy' mickmackusa --- 'What the_underscore ?!?' input 'what-the-underscore' expected 'what-theunderscore' SilentGhost 'what-the_underscore' mario 'What-theunderscore-' Rooneyl 'What-theunderscore-' AbhishekGoel 'What the_underscore ?!?' HelloHack 'What the_underscore ?!?' DenisMatafonov 'What-the_underscore-?!?' AdeelRazaAzeemi 'what-the-underscore' mickmackusa