I am inserting Alias field for my db called $alias how do I code (I am using php for mysql insert) to remove all spaces and replace space with "-" (trying to change it to "weburl format" ie removing spaces)
Thanks
I am inserting Alias field for my db called $alias how do I code (I am using php for mysql insert) to remove all spaces and replace space with "-" (trying to change it to "weburl format" ie removing spaces)
Thanks
For just removing spaces, you want the str_replace method. However, when working with URLs, you might want to consider the urlencode and rawurlencode methods as well.
Here's the method I use to santize strings for SEF urls:
$slug = trim(strtolower($value));
$slug = preg_replace('/[^a-z0-9 _-]/', '', $slug);
return preg_replace('/\s+/', '-', $slug);
Feel free to add additional allowed characters to the first regex.
Please note that this is NOT Unicode or even full ISO-8891 safe, well, it is, but it'll drop anything that isn't a-z
. That is, you may need to normalize the string beforehand (i.e., replace accented characters with their closes ASCII equivalent.) There's a number of SO questions and answers dealing with this that I've seen before, but I can't find them at the moment. I'll edit them in here if I stumble upon any.