user3590788
user3590788

Reputation: 11

Limiting the output of PHP to 100 characters

Am trying to limit the output of this code <tr><td valign=\"middle\" style=\"font-size:12px; padding-left:10px; padding-bottom:5px; height:10px\">".$postDetails['big_title']."</td></tr>

So it will be from this "blah blah blah blah" to 100 characthers "blah blah.." in UTF8?

Upvotes: 0

Views: 523

Answers (5)

Tim
Tim

Reputation: 125

The asker states that he wanted ellipses. I think a custom function would work very nice for this:

function limitOutput($string, $limit){
    if (strlen($string) > $limit){
        $string = substr($string, 0, $limit - 3) . '...';
    }
    return $string;
}

This can be used like so:

<tr><td valign=\"middle\" style=\"font-size:12px; padding-left:10px; padding-bottom:5px;height:10px\">".limitOutput($postDetails['big_title'],100)."</td></tr>

EDIT - Response to it not working:

<?php

function limitOutput($string, $limit){
    if (strlen($string) > $limit){
        $string = substr($string, 0, $limit - 3) . '...';
    }
    return $string;
}

$postDetails['big_title'] = str_repeat('12345678901234567890', 20);

echo $postDetails['big_title'].'<br><br>';

echo "<tr><td valign=\"middle\" style=\"font-size:12px; padding-left:10px; padding-bottom:5px;height:10px\">".limitOutput($postDetails['big_title'],100)."</td></tr>";

Upvotes: 0

sro
sro

Reputation: 1

<tr><td valign=\"middle\" style=\"font-size:12px; padding-left:10px; padding-bottom:5px; height:10px\">".substr($postDetails['big_title'], 0, 100)."</td></tr> add this , 0, 100, 'utf-8') ." …

Upvotes: -1

Kevin
Kevin

Reputation: 41885

Just check whether the string exceeds 100 chars, if yes, the use substr and append the ellipsis, if not just leave it as it is. Example:

$big_title = (strlen($postDetails['big_title']) > 100) ? substr($postDetails['big_title'], 0, 100) . '&hellip;' : $postDetails['big_title'];

echo "
    <tr>
        <td 
            valign=\"middle\" 
            style=\"font-size:12px; padding-left:10px; padding-bottom:5px; height:10px\"
        >"
        .$big_title.
        "</td>
    </tr>";

Upvotes: 0

jagmitg
jagmitg

Reputation: 4546

You can use

substr(strip_tags($postDetails['big_title']), 0, 70);

It will strip out any additional elements within the output.

Upvotes: 0

GHugo
GHugo

Reputation: 2654

Use the function substr to keep at most 100 characters of your string. Example:

<tr><td valign=\"middle\" style=\"font-size:12px; padding-left:10px; padding-bottom:5px; height:10px\">".substr($postDetails['big_title'], 0, 100)."</td></tr>

Upvotes: 2

Related Questions