PHP Regular expression - Remove all non-alphanumeric characters

后端 未结 4 956
无人共我
无人共我 2020-12-18 23:20

I use PHP.

My string can look like this

This is a string-test width åäö and some über+strange characters: _like this?

<

4条回答
  •  没有蜡笔的小新
    2020-12-18 23:27

    Are you perhaps looking for \W?

    Something like:

    /[\W_]*/
    

    Matches all non-alphanumeric character and underscores.

    \w matches all word character (alphabet, numeric, underscores)

    \W matches anything not in \w.

    So, \W matches any non-alphanumeric characters and you add the underscore since \W doesn't match underscores.

    EDIT: This make your line of code become:

    preg_replace("/[\W_]*/", ' ', $string);
    

    The ' ' means that all matching characters (those not letter and not number) will become white spaces.

    reEDIT: You might additionally want to use another preg_replace to remove all the consecutive spaces and replace them with a single space, otherwise you'll end up with:

    This is a string test width     and some  ber strange characters   like this 
    

    You can use:

    preg_replace("/\s+/", ' ', $string);
    

    And lastly trim the beginning and end spaces if any.

提交回复
热议问题