$string = 'Hello this is a bunch of numbers: 333 and letters and $pecial Characters@!*(';
$foo = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
echo $foo;
The above returns:
Hello this is a bunch of numbers 333 and letters and pecial Characters
I want to retain spaces but not if theres more than one. How can that be done?
It should look like:
开发者_如何学编程Hello this is a bunch of numbers 333 and letters and pecial Characters
$foo = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
$foo = preg_replace('/\s+/',' ',$foo);
One regex will do it:
$foo = preg_replace('/[^a-zA-Z0-9\s]|(\s)\s+/', '$1', $string);
I haven't worked with PHP, but in Perl it's something like:
s/\s+/ /g
i.e. replace any sequence of one or more spaces with a single space.
So I imagine the PHP to compress spaces would be:
$foo = preg_replace("/\s{2,}/", " ", $string);
I don't think there should be any problems with running two preg_replace lines, especially if it makes the code clearer.
Replace globally (edit - tested):
/(?<=\s)\s+|[^a-zA-Z0-9\s]+/
with ""
精彩评论