How to use substr_replace() for truncation with ellipsis In PHP
Using substr_replace()` in PHP truncates strings by replacing characters starting from a specified position. It’s effective for adding ellipses or other indicators when a string exceeds a desired length, providing concise summaries or previews.
Example:
<?php
$string = "This is a long sentence that needs to be truncated.";
$maxLength = 20;
if (strlen($string) > $maxLength) {
$truncatedString = substr_replace($string, '...', $maxLength);
} else {
$truncatedString = $string;
}
fwrite(STDOUT, $truncatedString . PHP_EOL);
?>
Output
This is a long sente...
How to limit string length in PHP ?
A string is a sequence of characters in PHP. The length of the string can be limited in PHP using various in-built functions, wherein the string character count can be restricted.
Table of Content
- Using for loop
- Using mb_strimwidth() function
- Using substr() method
- Using Regular Expressions with preg_match()
- Using substr_replace() for truncation with ellipsis