How do I write a regex in PHP to remove special characters?

后端 未结 3 922
盖世英雄少女心
盖世英雄少女心 2020-12-16 18:13

I\'m pretty new to PHP, and I noticed there are many different ways of handling regular expressions.

This is what I\'m currently using:

$replace = ar         


        
相关标签:
3条回答
  • 2020-12-16 18:55
    $newString = preg_replace('/[^a-z0-9]/i', '_', $join);
    

    This should do the trick.

    0 讨论(0)
  • 2020-12-16 18:59

    The easiest way is this:

    preg_replace('/\W/', '_', $join);
    

    \W is the non-word character group. A word character is a-z, A-Z, 0-9, and _. \W matches everything not previously mentioned*.

    Edit: preg uses Perl's regular expressions, documented in the perlman perlre document.

    *Edit 2: This assumes a C or one of the English locales. Other locales may have accented letters in the word character class. The Unicode locales will only consider characters below code point 128 to be characters.

    0 讨论(0)
  • 2020-12-16 19:04

    The regular expression for anything which isn't a-z, A-Z, 0-9 is:

    preg_replace('/[^a-zA-Z0-9]/', "_", $join);
    

    This is known as a Negated Character Class

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