mb_strimwidth

mb_strimwidth($string, $start, $width, $trim_marker, $encoding)

Shortens text to the given width and adds an ending to the shortened text, usually an ellipsis. Text that fits into the width is returned unchanged. It is useful for shortening titles and excerpts in listings.

Parameters

  • $string – the text to shorten.
  • $start – the position in characters where the text starts. Usually 0.
  • $width – the maximum width of the result including the ending. A common character has the width 1, Chinese, Japanese and Korean characters 2.
  • $trim_marker – optional, the text appended after the shortened text. The default is empty.
  • $encoding – optional, the character encoding. The default is the value of mb_internal_encoding(), usually UTF-8.

Examples

// width 15 including the ellipsis: 14 characters of text and the ellipsis
echo mb_strimwidth("Crème brûlée and café au lait", 0, 15, "…"); // Crème brûlée a…
// text that fits stays unchanged
echo mb_strimwidth("Short text", 0, 15, "…"); // Short text
// three dots take three characters of width
echo mb_strimwidth("Crème brûlée and café", 0, 10, "..."); // Crème b...
// without an ending
echo mb_strimwidth("Crème brûlée and café", 0, 10); // Crème brûl
// from position 6 (the seventh character)
echo mb_strimwidth("Crème brûlée and café", 6, 6); // brûlée
// strip the tags from text with HTML first
echo mb_strimwidth(strip_tags("<p>Long <b>text</b> of the article</p>"), 0, 10, "…"); // Long text…
// width is not the number of characters: Japanese characters have the width 2
echo mb_strwidth("café"); // 4
echo mb_strwidth("日本語"); // 6
echo mb_strimwidth("日本語のテキスト", 0, 7, "…"); // 日本語…

Things to watch out for

  • The width includes the ending. With the width 15 and an ellipsis 14 characters of the text remain.
  • It also cuts in the middle of a word. Shortening to a whole word can be built from mb_substr() and mb_strrpos().
  • Do not shorten text with HTML tags or entities. The cut can end in the middle of a tag or an entity (&amp;) and break the page. Shorten the plain text and only then escape the result with htmlspecialchars().
  • For European languages the width equals the number of characters. Characters of double width concern mainly Chinese, Japanese and Korean.
  • When it is only about the look (the text does not fit into a line), CSS can shorten it too: text-overflow: ellipsis. The whole text then stays in the page.

Related functions:
mb_substr()
mb_strlen()
mb_strrpos()
mb_strwidth()