Why use multibyte string functions in PHP?

后端 未结 6 1787
情话喂你
情话喂你 2020-12-16 18:49

At the moment, I don\'t understand why it is really important to use mbstring functions in PHP when dealing with UTF-8? My locale under linux is already set

6条回答
  •  不思量自难忘°
    2020-12-16 19:18

    Raul González is a perfect example of why:

    It is about shortening too long user names for MySQL database, say we have 10 character limit and Raul González.

    The unit test below is an example how you can get an error like this

    General error: 1366 Incorrect string value: '\xC3' for column 'name' at row 1 (SQL: update users set name = Raul Gonz▒, updated_at = 2019-03-04 04:28:46 where id = 793)

    and how you can avoid it

    public function test_substr(): void
    {
        $name = 'Raul González';
        $user = factory(User::class)->create(['name' => $name]);
        try {
            $name1      = substr($name, 0, 10);
            $user->name = $name1;
            $user->save();
        } catch (Exception $ex) {
    
        }
        $this->assertTrue(isset($ex));
    
        $name2      = mb_substr($name, 0, 10);
        $user->name = $name2;
        $user->save();
    
        $this->assertTrue(true);
    }
    

    PHP Laravel and PhpUnit was used for illustration.

提交回复
热议问题