Jenz
Jenz

Reputation: 8369

Not returning desired substring when strpos is used for making sure that it ends with a word only

I am using the following function for extracting substring from a description field and also make sure that it ends with a complete word only.

function smalldescription($msg)
{
    $message=substr($msg, 0, strpos($msg, ' ', 500));
    $message=$message."...";
    return $message;
}

My problem is, if the $msg is a lenghty description, then the function is returning 500 characters finely. But if $msg is not a lengthy description, say only 20 characters, then the resultant string is as ... only. Can anyone help me to solve the problem.

Upvotes: 1

Views: 76

Answers (1)

KarSho
KarSho

Reputation: 5746

see this

function smalldescription($msg)
{

if (strlen($msg) > 500)
{
    $message=substr($msg, 0, strpos($msg, ' ', 500));
    $message=$message."...";
    return $message;
}
else
{
     return $msg;
}

}

Upvotes: 1

Related Questions