As you know, you can remove these characters like this:
$result = preg_replace("/[a-zA-Z0-9]/", "", $text);
So, in order to get what you want (save these characters, delete any others), we need to "invert" this:
$result = preg_replace("/[^a-zA-Z0-9]/", "", $text);
You can also use \ W to remove something “non-verbal”:
$result = preg_replace("/\W/", "", $text);
The word symbol is any letter or number or underscore, that is, any symbol that can be part of the word Perl. The definition of letters and numbers is controlled by the PCRE character tables and may vary if language matching occurs. For example, in "fr" (French), for accented characters, some character codes greater than 128 are used, and they correspond to \ w.
http://www.php.net/manual/en/regexp.reference.escape.php
source share