Cøde Play Cøde Play - 1 year ago 72
PHP Question

Am I misunderstanding strlen()?

I'm trying to properly understand

in PHP to make a application where text is shortened and finished with a

My code:

$prize_text = "Learn how to eat pizza TODAY";
if (strlen($prize_text) > 24) {
$prize_text = substr($prize_text, 0, 21) . '...';

#1 Visual Aid

$prize_text = "Watch Good Day Sunshine Today!";

#2 Visual Aid

$prize_text = "abcdefghijklmnopqrstuvwxyz";

#3 Visual Aid

Why is everything not matching up? I want one uniform standard of shortening the text and then appending three dots. What is wrong with my code?

Answer Source

Wrong tool for the job. You want CSS instead to avoid the breaking problem you're having.

#element {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;


  • You can hide/show the text at will, whereas with PHP the text sent is already rendered in the document.
  • Will work for multiple situations whereas the PHP is hard-coded.