I wrote this code to prepare a title for a link, but I think it is a bit bulky and am wondering if anyone with a better understanding of regex would be able to reduce the following function (by merging the relevant preg_replaces). I need it to strip all current hyphens, strip multiple spaces, ensure that it is solely alphanumeric apart from the space-replacing hyphen, replace all spaces with a single hyphen and ensure that the string doesn't start with a hyphen:
function prepareURLTitle($title)
{
return preg_replace("/\A-/", "", str_replace(" ", "-", preg_replace("/[^a-zA-Z0-9\s]/", "", preg_replace('/\s\s+/', ' ', preg_replace('/\s?-/', '', $title)))));
}
An example of input and it's output:
Input:
BRAND NEW - Gloves, 2 pack //Multiple spaces are in here but the blockquote won't allow me to display them
Output:
BRAND-NEW-Gloves-2-pack