25

How can I use PHP to strip out all characters that are NOT alpha, numeric, space, or puncutation?

I've tried the following, but it strip punctuation.

preg_replace("/[^a-zA-Z0-9\s]/", "", $str);
Tedd
  • 253
  • 1
  • 3
  • 5

3 Answers3

32
preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", $str);

Example:

php > echo preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", "⟺f✆oo☃. ba⟗r!");
foo. bar!

\p{P} matches all Unicode punctuation characters (see Unicode character properties). If you only want to allow specific punctuation, simply add them to the negated character class. E.g:

preg_replace("/[^a-zA-Z0-9\s.?!]/", "", $str);
Matthew Flaschen
  • 268,153
  • 48
  • 509
  • 534
  • The second would. The first allows all punctuation. – Matthew Flaschen Jun 16 '10 at 02:36
  • These seem to strip ALL characters :( – Tedd Jun 16 '10 at 02:42
  • I'm using your first example and this seem to strip all characters. What am I doing wrong? – Tedd Jun 16 '10 at 02:45
  • @Tedd, not sure. I posted a tested example. The [docs](http://www.php.net/manual/en/regexp.reference.unicode.php) mention a couple caveats. You have to use PHP after 4.4 or 5.1 (depending on branch), and UTF-8, and the PCRE library has to be compiled with `--enable-unicode-properties` – Matthew Flaschen Jun 16 '10 at 16:00
3

You're going to have to list the punctuation explicitly as there is no shorthand for that (eg \s is shorthand for white space characters).

preg_replace('/[^a-zA-Z0-9\s\-=+\|!@#$%^&*()`~\[\]{};:\'",<.>\/?]/', '', $str);
cletus
  • 599,013
  • 161
  • 897
  • 938
0
$str = trim($str);
$str = trim($str, "\x00..\x1F");
$str = str_replace(array( "&quot;","&#039;","&amp;","&lt;","&gt;"),' ',$str);
$str = preg_replace('/[^0-9a-zA-Z-]/', ' ', $str);
$str = preg_replace('/\s\s+/', ' ', $str); 
$str = trim($str);
$str = preg_replace('/[ ]/', '-', $str);

Hope this helps.

Yuck
  • 47,217
  • 13
  • 101
  • 134
MojganK
  • 201
  • 3
  • 7