I am having trouble with string manipulation in php. I am writing a function that with take a string parameter that has words separated with either " " or "_". I want the function to remove all non alphabetic characters and return the words separated with a "-". This is what I have so far:
function cleanCategoryForUrl($strCategory){
$newCategory = str_replace('_', '-', $strCategory); //First replacement
echo ($newCategory);
$newCategory = str_replace(' ', '-', $newCategory); //Second replacement
echo ($newCategory);
$newCategory = preg_replace('/[^a-z-]/i', '', $strCategory); //Final replacement
echo ($newCategory);
return $newCategory;
}
The first and second replacements will get make the words separated with "-" instead of " " or "_". The final replacement will get red of all characters that are not alphabetic or a "-".
But when I test the code, I get unexpected results after the final replacement.
With an input of "Home_Health" I get this printed:
Home-Health
Home-Health
HomeHealth
The first two outputs are as expected, but third one removed the "-" (which shouldn't have happened). I suspect something is wrong with my regex pattern, but it words fine when I test it on http://gskinner.com/RegExr/. I am new to using regex and cant figure out what is wrong. Please Help