Convert string into slug with single-hyphen delimiters only Convert string into slug with single-hyphen delimiters only php php

Convert string into slug with single-hyphen delimiters only


function slug($z){    $z = strtolower($z);    $z = preg_replace('/[^a-z0-9 -]+/', '', $z);    $z = str_replace(' ', '-', $z);    return trim($z, '-');}


First strip unwanted characters

$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);

Then changes spaces for unserscores

$url = preg_replace('/\s/', '-', $new_string);

Finally encode it ready for use

$new_url = urlencode($url);


This will do it in a Unix shell (I just tried it on my MacOS):

$ tr -cs A-Za-z '-' < infile.txt > outfile.txt

I got the idea from a blog post on More Shell, Less Egg