I’m in need to modify a given string to contain only alpha numerical characters, dots (.) and commas.
If the string contains any character other than a-z, A-Z , 0-9 or a dot(.), they should be replaced with a comma sign, I’m using this:
$string = "dycloro 987 stackOVERflow !|,!!friday";
$newstring = preg_replace('/[^a-zA-Z0-9\.]/', ',', $string);
This returns,
dycloro,987,stackOVERflow,,,,,,friday
But I’m in need to get the following instead.
dycloro,987,stackOVERflow,friday
(Note the ” !|,!!” part in $string is replaced with a single comma sign).
Ideally, I want to replace a block of disallowed characters with a single comma sign.
I figured out that
$newstring = preg_replace('/,{2,}/', ',', $newstring); replaces multiple comma signs with a single comma. But is there any way to do this in a faster, or better way ?
How do I do this in a single regular expression match ?
and is there any process time or memory difference in them ? This is regular expressions will be run against few megabytes of user input so I’m curious about it as well.
Thank you!
Just add a plus sign
+, meaning “one or more of what I just mentioned”, after the character class:See http://www.php.net/manual/en/regexp.reference.repetition.php.