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?

Recommended Answers

All 4 Replies

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():

if(ctype_space($string))
{
   $string = substr($string, 0, strrpos($string, ' '));
}

bye :)

commented: tq dude +2

Also, its bad practice to write your php tags in shorthand.

Member Avatar for diafol
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 (...).

tq dude. it is solved :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.