Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate an UTF8 string in PHP?

I have some strings in my PHP code that need to be truncated if they are too long.

For example if a text is something like this:

Hi, I would like to tell you how wonderful this is.

It would replace it with this:

Hi, I would like to ...

For that I've done a simple substr. The problem is that in UTF8 some characters are actually two characters long. And I've had some problems with a character being cut in the middle: For example, when I try to insert the modified string in the database, it crashes.

Here is my current function:

static function short($string, $max = 255){
   if(strlen($string) >= $max){
       $string = substr($string, 0, $max - 5).'...';
   } return $string;
}

Would someone know a way to make this function work even for UTF8 characters?

like image 721
Andrei Avatar asked Dec 13 '11 04:12

Andrei


People also ask

How to truncate string in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

How can I truncate a string to the first 20 words in PHP?

use PHP tokenizer function strtok() in a loop.


2 Answers

Everything you need is mb_strimwidth() : http://php.net/manual/en/function.mb-strimwidth.php

Example:

mb_strimwidth('Hi, I would like to tell you how wonderful this is.',0,15,'...','utf-8');
like image 92
Timur Avatar answered Oct 09 '22 00:10

Timur


try with mb_substr() :

static function short($string, $max = 255){
   if(mb_strlen($string, 'utf-8') >= $max){
       $string = mb_substr($string, 0, $max - 5, 'utf-8').'...';
   } return $string;
}
like image 31
Tudor Constantin Avatar answered Oct 09 '22 00:10

Tudor Constantin