What are the potential pitfalls of using substr() in PHP to limit the length of a string for display in HTML?
Using substr() to limit the length of a string for display in HTML can potentially cut off the string in the middle of a word, causing readability issues. To solve this problem, we can use the mb_substr() function instead, which handles multi-byte characters properly and ensures that the string is cut off at a valid point.
<?php
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$maxLength = 20;
if(mb_strlen($string) > $maxLength){
$trimmedString = mb_substr($string, 0, $maxLength) . "...";
} else {
$trimmedString = $string;
}
echo $trimmedString;
?>
Keywords
Related Questions
- What are some common pitfalls to avoid when coding a script to display online users in PHP?
- What are some best practices for handling headers in PHP when serving mp3 files?
- Are there any specific date formatting considerations that should be taken into account when working with date-based image outputs in PHP?