I have a code to trim the long word for the specific length and replace it with '...' but, it has a problem, where, if user's name dont have space, its will look wierd..

heres the code:

function truncateString($string, $length, $append = '...') {
    $length -= strlen($append); // length of "..."

    $string = substr($string, 0, $length);
    $string = substr($string, 0, strrpos($string, ' '));
    $string .= $append;

    return $string;

//to test the function
echo truncateString('My very long title', 15);

1. if value has space,it will look nice
exp: John Mayer ...

2. if dont have space
exp: ...

How to fix it?

6 Years
Discussion Span
Last Post by dean8710

From substr() manual:

string substr ( string $string , int $start [, int $length ] )
If length is given and is 0, FALSE or NULL an empty string will be returned.

The problem is related to substr() on line 6, because strrpos() returns FALSE when there are no spaces:

$string = substr($string, 0, strrpos($string, ' '));

therefore you have substr('nospacestring',0,false) In order to solve change that line with this, which makes use of ctype_space():

   $string = substr($string, 0, strrpos($string, ' '));

bye :)

Votes + Comments
tq dude
mb_strimwidth("Hello World How are You?", 0, 10, "...");

Will cut your characters to 7 chars + 3 lots of dots (10 chars).
If you want 10 chars then the ..., use:

mb_strimwidth("Hello World How are You?", 0, 13, "...");

Does it matter if you truncate a part of the word/name?

Equally you could use substr() and add the ellipsis (...).

Edited by diafol: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.