Regex: Strip non alpha numeric or punctuation

前端 未结 3 429
轮回少年
轮回少年 2020-12-09 16:12

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.



        
3条回答
  •  半阙折子戏
    2020-12-09 16:36

    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);
    

提交回复
热议问题