Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut strings short PHP

Tags:

string

php

How would you go about Cutting strings short so it doesnt go to the next line in a div tag For example my message string contained the following:

We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply. If your question is about this website, ask it on meta instead.

And i want to preferably display it as

We prefer questions that can be answered, not just discussed. Provide ... Read More

Im thinking cutting the string short using PHP but then you have the following problem

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ... Read More

You can see that the above string can still be expanded a bit more. Any way to do this or Not, Thanks in Advance

like image 711
Angel.King.47 Avatar asked Dec 05 '25 17:12

Angel.King.47


2 Answers

How you can shorten a string is already answered, but your main question:

How would you go about Cutting strings short so it doesnt go to the next line in a div tag

this will not work in most cases.

for example:

iiiiiiiiii

wwwwwwwwww

You see the problem ?

this only works if your chars have the same width like:

iiiiiiiiii
wwwwwwwwww
like image 59
Rufinus Avatar answered Dec 08 '25 10:12

Rufinus


Using PHP, you can use the wordwrap function to perform truncation:

function truncate_to_length($text, $length, $text_if_longer = "...") 
{
    if (strlen($text) > $length) 
    {
        $text = wordwrap($text, $length);
        $text = substr($text, 0, strpos($text, "\n"));
        return $text . $text_if_longer;
    }
    return $text;
}
like image 33
John Rasch Avatar answered Dec 08 '25 09:12

John Rasch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!