Stripping everything but alphanumeric chars from a string in PHP

后端 未结 5 2055
花落未央
花落未央 2020-12-08 19:08

I\'d like a regexp or other string which can replace everything except alphanumeric chars (a-z and 0-9) from a string. All things such as ,@#

相关标签:
5条回答
  • 2020-12-08 19:26

    This also works to replace anything not a digit, a word character, or a period with an underscore. Useful for filenames.

    $clean = preg_replace('/[^\d\w.]+/', '_', $string);
    
    0 讨论(0)
  • 2020-12-08 19:32

    I like using [^[:alnum:]] for this, less room for error.

    preg_replace('/[^[:alnum:]]/', '', "(ABC)-[123]"); // returns 'ABC123'
    
    0 讨论(0)
  • 2020-12-08 19:35
    /[^a-z0-9.]/
    

    should do the trick

    0 讨论(0)
  • 2020-12-08 19:42
    $string = preg_replace("/[^a-z0-9.]+/i", "", $string);
    

    Matches one or more characters not a-z 0-9 [case-insensitive], or "." and replaces with ""

    0 讨论(0)
  • 2020-12-08 19:46

    Try:

    $string = preg_replace ('/[^a-z0-9]/i', '', $string);
    

    /i stands for case insensitivity (if you need it, of course).

    0 讨论(0)
提交回复
热议问题