php, if text string long than 40 characters, just get first 40 characters and add "..."…
Jump to turn (6)
- User
php, if text string long than 40 characters, just get first 40 characters and add "..." at then end, else get all characters. The text string may be Chinese character (double bytes)
- Assistant
Here's one way to do it in PHP:
codefunction truncateText($text, $length = 40) { if (mb_strlen($text, 'utf-8') > $length) { $text = mb_substr($text, 0, $length, 'utf-8') . '...'; } return $text; }This function takes a string
$textand an optional parameter$length(default is 40) and returns the truncated string with "..." added at the end if the length is greater than$length. Themb_strlenandmb_substrfunctions are used to handle multibyte (Chinese) characters properly. Here's an example usage: