Search code examples
algorithmellipsis

Issue with algorithm to shorten sentences


I have a webpage which displays multiple textual entries which have no restriction on their length. They get automatically cut if they are too long to avoid going to a new line. This is the PHP function to cut them:

function cutSentence($sentence, $maxlen = 16) {
    $result = trim(substr($sentence, 0, $maxlen));

    $resultarr = array(
            'result' => $result,
            'islong' => (strlen($sentence) > $maxlen) ? true : false    
        );

    return $resultarr;
}

As you can see in the image below, the result is fine, but there are a few exceptions. A string containing multiple Ms (I have to account for those) will go to a newline.

Right now all strings get cut after just 16 characters, which is already very low and makes them hard to read.

I'd like to know if a way exists to make sure sentences which deserve more spaces get it and those which contain wide characters end up being cut at a lower number of characters (please do not suggest using the CSS property text-overflow: ellipsis because it's not widely supported and it won't allow me to make the "..." click-able to link to the complete entry, and I need this at all costs).

Thanks in advance.


Solution

  • If the style of your application isn't too important, you could simply use a font in the monospace family such as Courier.