In several situations, the need arises to limit the number of characters to be displayed from a string in php. In this post we will see perhaps the easiest way to do this, using the mb_strimwidth function.
To use the mb_strimwidth function we pass 4 parameters: the string to be delimited; the starting character position; the final character position; a static text to be concatenated at the end (Ex: …) (NOTE: The static text at the end enters the count)
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php $text = "Edward Lodewijk Van Halen (January 26, 1955 – October 6, 2020), was an American musician and songwriter. He was the main songwriter, guitarist and keyboardist of the rock band Van Halen, which he co-founded in 1972 with his brother, drummer Alex Van Halen, alongside bassist Mark Stone and singer David Lee Roth."; echo mb_strimwidth($text, 0, 120, '...'); /* output: Edward Lodewijk Van Halen (January 26, 1955 – October 6, 2020), was an American musician and songwriter. He was... */
In the example above, we use the mb_strimwidth function to print the variable $text from position 0 to 120, inserting the “…” at the end. Therefore, 117 characters will be printed plus the 3 dots.