i am batman
i am batman

Reputation: 669

How do I get all the words for certain character limit

Lets say I have a description of 500 characters. I need to limit the characters into 200. Then I remove the last word to make sure that I have no broken words.

This works for the English contents but doesn't work for other languages like Japanese or traditional Chinese. When I limit a Japanese or Chinese description it gives a special character at the end like this �.

Below is my code and is there a way to overcome this?

function getLimitDescription($description, $limit)
{
    $limitedDesc  = substr($description, 0, $limit);

    // Remove the last word of the limited description
    $limitedDesc = preg_replace('/\W\w+\s*(\W*)$/', '$1', $limitedDesc);
    $lastChar    = substr($limitedDesc, -1);

    if (preg_match("/[\'^£$%&*()}{@#~?><>;,|=_+¬-]/", $lastChar))
    {
        $limitedDesc = substr($limitedDesc, 0, -1);
    }

    return $limitedDesc;
}

Upvotes: 0

Views: 69

Answers (1)

Andreas
Andreas

Reputation: 23958

You don't need to use regex. Just use strrpos and find the next space from right.

function getLimitDescription($description, $limit)
{
    $limitedDesc  = substr($description, 0, $limit);
    $pos = strrpos($limitedDesc, " ");
    $limitedDesc  = substr($limitedDesc, 0, $pos);
    return $limitedDesc;
}

echo getLimitDescription("Insert long string right here", 17);

https://3v4l.org/eao6F

Upvotes: 1

Related Questions