Multibyte trim in PHP?

后端 未结 8 1489
小鲜肉
小鲜肉 2020-11-28 08:19

Apparently there\'s no mb_trim in the mb_* family, so I\'m trying to implement one for my own.

I recently found this regex in a comment in php.net:

相关标签:
8条回答
  • 2020-11-28 09:20

    Ok, so I took @edson-medina's solution and fixed a bug and added some unit tests. Here's the 3 functions we use to give mb counterparts to trim, rtrim, and ltrim.

    ////////////////////////////////////////////////////////////////////////////////////
    //Add some multibyte core functions not in PHP
    ////////////////////////////////////////////////////////////////////////////////////
    function mb_trim($string, $charlist = null) {
        if (is_null($charlist)) {
            return trim($string);
        } else {
            $charlist = preg_quote($charlist, '/');
            return preg_replace("/(^[$charlist]+)|([$charlist]+$)/us", '', $string);
        }
    }
    function mb_rtrim($string, $charlist = null) {
        if (is_null($charlist)) {
            return rtrim($string);
        } else {
            $charlist = preg_quote($charlist, '/');
            return preg_replace("/([$charlist]+$)/us", '', $string);
        }
    }
    function mb_ltrim($string, $charlist = null) {
        if (is_null($charlist)) {
            return ltrim($string);
        } else {
            $charlist = preg_quote($charlist, '/');
            return preg_replace("/(^[$charlist]+)/us", '', $string);
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////
    

    Here's the unit tests I wrote for anyone interested:

    public function test_trim() {
        $this->assertEquals(trim(' foo '), mb_trim(' foo '));
        $this->assertEquals(trim(' foo ', ' o'), mb_trim(' foo ', ' o'));
        $this->assertEquals('foo', mb_trim(' Åfooホ ', ' Åホ'));
    }
    
    public function test_rtrim() {
        $this->assertEquals(rtrim(' foo '), mb_rtrim(' foo '));
        $this->assertEquals(rtrim(' foo ', ' o'), mb_rtrim(' foo ', ' o'));
        $this->assertEquals('foo', mb_rtrim('fooホ ', ' ホ'));
    }
    
    public function test_ltrim() {
        $this->assertEquals(ltrim(' foo '), mb_ltrim(' foo '));
        $this->assertEquals(ltrim(' foo ', ' o'), mb_ltrim(' foo ', ' o'));
        $this->assertEquals('foo', mb_ltrim(' Åfoo', ' Å'));
    }
    
    0 讨论(0)
  • 2020-11-28 09:22

    I don't know what you're trying to do with that endless recursive function you're defining, but if you just want a multibyte-safe trim, this will work.

    function mb_trim($str) {
      return preg_replace("/^\s+|\s+$/u", "", $str); 
    }
    
    0 讨论(0)
提交回复
热议问题