A few of you regular expression gurus should find this easy.... Basically I have a string and I want to strip out anything thats not alphanumeric, and i want to replace any spaces with a - So for example this string: t2es% no* *ss3aa would become: t2es-no-ss3aa If anyone could write the preg_replace to do that Id appreciate it!
<?php function replace($str){ $string_array = str_split($str); $count = 0; foreach($string_array as $char){ if(!preg_match("([a-zA-Z0-9_-]+)",$char)){ $string_array[$count]="-"; } $count++; } $check = 0; foreach($string_array as $checkchar){ if($checkchar=="-"){ if($checkchar == $string_array[$check+1]||$checkchar == $string_array[$check-1]){ unset($string_array[$check]); } $check++; }else{ $check++; } } $string = implode("",$string_array); echo $string; } ?> PHP: this works... probably a little heavy... but it works haha
Try this: $newString = preg_replace('/\s/', '-', preg_replace(array('/[^a-z0-9\s]/i'), array(''), $originalString)); PHP:
The idea of using arrays is good, but rather pointless the way you do it. I'd do it this way: $text = preg_replace(array('~\s+~', '~[^a-z0-9-]~i'), array('-', ''), $text); PHP:
nico_swd: Thanks for the correction, nico_swd. I was initially gonna suggest the same way like you posted above, but then realised that if the original string had a dash ('-') character in it, it wouldn't be removed (while it is a non-alphanumeric character). e.g.: "x%- g" would become "x--g" instead of "x-g" After I updated it then I forgot to take the value out of the array ruby: Thanks for the rep Regarding nico_swd's correction above, it wouldn't affect the result at all if you just keep your code like what you have now. But if you are really keen, below is a cleaner code: $newString = preg_replace('/\s/', '-', preg_replace('/[^a-z0-9\s]/i', '', $originalString)); PHP: