php

PHP Shorten String With Three Dots

Using PHP, we can shorten the length of our string and just replace the rest with three dots.

This is usually needed in a software application, especially when the string length is too long to show to the user.

So we will write a function that is re-usable and which we can always call or use in any other programming.

 function trimString($string, $repl, $limit) 
{
  if(strlen($string) > $limit) 
  {
    return substr($string, 12, $limit) . $repl; 
  }
  else 
  {
    return $string;
  }
}
?>

 echo trimString("Hello Codeflare", "...", 3);

Explanation

The trimString function we created takes three (3) parameters:

  1. The string which we want to shorten,
  2. What we want to replace the cut out section with, which in this case is three (3) dots
  3. And the limit or length of string.

Next, we check if the length of the given string is greater than the limit which we have set. If it is, we truncate it and append our three dots. If it’s not, we just return the given string.

Conclusion

This is how we shorten the length of a string and replace it with three (3) dots in PHP.

Let me know what you think in the comments.

See Also:

Image Upload With Preview Using PHP’s PDO And jQuery

Enrol for Software Development Training

Author

Recent Posts

Google Launches Its Own ‘Reasoning’ AI Model to Compete with OpenAI

This month has been packed for Google as it ramps up efforts to outshine OpenAI…

2 days ago

You can now use your phone line to call ChatGPT when cellular data is unavailable.

OpenAI has been rolling out a series of exciting updates and features for ChatGPT, and…

3 days ago

Phishers use fake Google Calendar invites to target victims

A financially motivated phishing campaign has targeted around 300 organizations, with over 4,000 spoofed emails…

4 days ago

Hackers Exploiting Microsoft Teams to Remotely Access Users’ Systems

Hackers are exploiting Microsoft Teams to deceive users into installing remote access tools, granting attackers…

5 days ago

Ethical Hacking Essentials

Data plays an essential role in our lives.  We each consume and produce huge amounts…

7 days ago

Thomas E. Kurtz, co-creator of the BASIC programming language, passes away at 96.

Thomas E. Kurtz, co-creator of the BASIC programming language, passed away on November 12, 2024,…

7 days ago