isedeasy Posted January 19, 2011 Share Posted January 19, 2011 I have a function that replaces certain characters with a hyphen function addHyphens($string) { $chars = array(" ", "&", "_", "/", "\\", "(", ")", "#", "?", "%", "\"","'", ".", ",", ":", ";", "[", "]", "!", "$", "£", "+", "="); $newstring = str_replace( $chars, '-', $string); return $newstring; } at the minute I get echo addHyphens('foo - bar'); // returns foo---bar echo addHyphens('foo! bar!'); // returns foo--bar- I would like the following to happen echo addHyphens('foo - bar'); // returns foo-bar echo addHyphens('foo! bar!'); // returns foo-bar What's the best way to go about this? Quote Link to comment https://forums.phpfreaks.com/topic/225013-replacing-characters/ Share on other sites More sharing options...
Coolkat Posted January 19, 2011 Share Posted January 19, 2011 to get both of those to work you'll have to replace all spaces with a - and all other symbols with a nothing.. try: function addHyphens($string) { $chars = array("&", "_", "/", "\\", "(", ")", "#", "?", "%", "\"","'", ".", ",", ":", ";", "[", "]", "!", "$", "£", "+", "="); $string = str_replace( $chars, '', $string); $string = str_replace( ' ', '-', $string); return $string; } Quote Link to comment https://forums.phpfreaks.com/topic/225013-replacing-characters/#findComment-1162214 Share on other sites More sharing options...
isedeasy Posted January 19, 2011 Author Share Posted January 19, 2011 Ah yeah did not think of that. Cheers Quote Link to comment https://forums.phpfreaks.com/topic/225013-replacing-characters/#findComment-1162219 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.