What are the potential pitfalls of using substr() to limit the length of a string in PHP?
Using substr() to limit the length of a string in PHP can potentially lead to unintended truncation of the string, cutting off in the middle of a word or sentence. To avoid this issue, it's recommended to use mb_substr() instead, which handles multi-byte characters correctly.
// Using mb_substr() to limit the length of a string without cutting off in the middle of a multi-byte character
$originalString = "This is a sample string with multi-byte characters: café";
$maxLength = 10;
if(mb_strlen($originalString) > $maxLength) {
$truncatedString = mb_substr($originalString, 0, $maxLength) . "...";
} else {
$truncatedString = $originalString;
}
echo $truncatedString;
Related questions
-
CSV files PHP handling
-
MySQLi PDO connection pooling
-
SQL injection htmlspecialchars htmlentities