How to Truncate a String in PHP?


The following is a PHP Function that allows us to truncate a string (and optionally appended with suffix e.g. dots) if the length exceeded the threshold. Otherwise, the function returns the string itself.

1
2
3
4
5
6
<?php
if (!function_exists("truncate")) {
  function truncate($string, $length, $dots = "...") {
      return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
  }
}
<?php
if (!function_exists("truncate")) {
  function truncate($string, $length, $dots = "...") {
      return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
  }
}

For example:

1
2
3
4
<?php
 
echo truncate("Hello, world", 1000, ".."); // "Hello, world"
echo truncate("Hello, world", 5, "..."); // "Hello..."
<?php

echo truncate("Hello, world", 1000, ".."); // "Hello, world"
echo truncate("Hello, world", 5, "..."); // "Hello..."

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
144 words
Last Post: Teaching Kids Programming - Subtree with Maximum Value via Recursive Depth First Search Algorithm
Next Post: How to Exit Your Background Process that Takes Too Long to Run using NodeJs?

The Permanent URL is: How to Truncate a String in PHP?

Leave a Reply