Replace spaces with a dash in a URL
You can use preg_replace:
preg_replace('/[[:space:]]+/', '-', $subject);
This will replace all instances of space with a single '-' dash. So if you have a double, triple, etc space, then it will still give you one dash.
EDIT: this is a generec function I've used for the last year to make my URLs tidy
function formatUrl($str, $sep='-') { $res = strtolower($str); $res = preg_replace('/[^[:alnum:]]/', ' ', $res); $res = preg_replace('/[[:space:]]+/', $sep, $res); return trim($res, $sep); }
It will convert all non-alphanumeric characters to space, then convert all space to dash, then trim any dashes on the end / beginning of the string. This will work better than having to list special characters in your str_replace