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
<?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

Similar Reads

Using for loop

The str_split() function can be used to convert the specified string into the array object. The array elements are individual characters stored at individual indices....

Using mb_strimwidth() function

The mb_strimwidth function is used to get truncated string with specified width. It takes as input the string and the required number of characters. The characters after it are appended with an “!!” string. It returns the string with the trimmed length....

Using substr() method

The substr() function can be used to extract the specified string within the specified limits. The starting and ending indexes are specified and the equivalent number of characters between the start and end length are extracted....

Using Regular Expressions with preg_match()

Using preg_match() with a regular expression, you can limit the length of a string by matching the first few characters. The pattern /.{0,5}/ captures up to the first 5 characters....

Using substr_replace() for truncation with ellipsis

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....