search

Home  >  Q&A  >  body text

php replaces all symbols or spaces in the string with "-"

How to replace all symbols or spaces in a string of words with "-"
Including,? @%! $&*(whatever)

PHPzPHPz2831 days ago626

reply all(3)I'll reply

  • 習慣沉默

    習慣沉默2017-05-16 13:18:12

    $result = preg_replace('/[^w]|[_]/', '「-」', $str);
    匹配替换非字母数字并替换。
    w包括_,如果想一并替换掉,再添加上 |[_].


    Reply to comment:
    If you want to replace characters other than Chinese and English, change the pattern to the following form:
    /[^bA-Za-zx{4e00}-x{9fa5}]/u /[^bA-Za-zx{4e00}-x{9fa5}]/u
    b 表示空格;
    u4e00-u9fa5是unicode里中文的表示法,但preg_replace不支持u的写法,可以使用 x{XXXX}来替代;
    最后使用ub represents a space;

    u4e00-u9fa5 is the representation of Chinese in unicode, but preg_replace does not support the writing method of u, you can use x{XXXX} instead; 🎜Finally use the u option to indicate that the utf-8 character set is used. 🎜

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-16 13:18:12

    Call removeXss()

    reply
    0
  • 迷茫

    迷茫2017-05-16 13:18:12

    preg_replace is one method, here I provide another method, see the code below

        $str = 'hello %abc?11';
        $patten = array(
            '【',
            '】',
            '「',
            '?',
            '%',
            '&'
        );
    
        $rs = str_replace(' ','',str_replace($patten,'「-」',$str));
        echo $rs;

    reply
    0
  • Cancelreply