How can I use PHP to strip out all characters that are NOT letters, numbers, spaces, or punctuation marks?
I’ve tried the following, but it strips punctuation.
JavaScript
x
preg_replace("/[^a-zA-Z0-9s]/", "", $str);
Advertisement
Answer
JavaScript
preg_replace("/[^a-zA-Z0-9sp{P}]/", "", $str);
Example:
JavaScript
php > echo preg_replace("/[^a-zA-Z0-9sp{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:
JavaScript
preg_replace("/[^a-zA-Z0-9s.?!]/", "", $str);