1
$outputstr = preg_replace('/[-]{2,}/','-',trim(strtolower(str_replace(' ','-',preg_replace('/[^A-Z0-9- ]+/i','',$inputstr))),'-'));
Refactorings
No refactoring yet !
Christoffer
February 9, 2010, February 09, 2010 08:13, permalink
A little longer but easier on the eyes :)
1 2 3 4 5 6 7 8 9
<?php function clean_string($str) { $str = trim(strtolower($str)); $str = preg_replace('/\s+/i', '-', $str); $str = preg_replace('/[^a-z0-9\-\._]/i', '', $str); return $str; } ?>
Max
March 4, 2010, March 04, 2010 16:04, permalink
A compromise of readability and conciseness
1 2 3 4 5 6
<?php function clean_string($str) { $str = trim(strtolower($str)); return preg_replace(array('/[^\w]+/', '/(^-+|-+$|[-]{2,})/'), array('-', ''), $str); } ?>
I'm trying to get an input string to get rid of all characters except alpha-numerics, hyphen and a space, then the result i would like any hyphens at the start and at the end removed, also, if there are more than one hyphen in a row, to just replace it with one, and change the whole thing to lower case e.g :
-!! This is a "**Test- -string**" !!!!-
results to :
this-is-a-test-string
The code works fine, but it seems a bit long-winded the way i've done it, can this code be refactored at all?