When content is displayed in a multi-column layout, the amount of horizontal space can be limited. This means that we can have a restricted amount of space to display text content.
Especially with dynamic content such as a grid of blog posts or products, the description text can be too long. It can therefore be useful to to create a PHP function that limits the number of characters to a more manageable amount:
The function works by taking two parameters: the original piece of text and the number of characters we want to be the limit. We can set the limit in the function parameter if there is a common limit that is used throughout the website.
Inside the function, we set the returned text equal to the piece of text we passed to the function. This way, if the text is already short enough, we can do nothing and leave it alone.
If the number of characters in the text is larger than the limit, we can use the substr() function to reduce the output text. Finally, we add the ellipsis to the end of the text so it is clear to the user that the text has been reduced.
What’s the Chat?