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

390

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.

520

Answer

Solution:

see this

function smalldescription($msg)
{

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

}

People are also looking for solutions to the problem: PHP form appears below again after submitting

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.