Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

php - Trim headline to nearest word

Say for example I have the following code:

<h3>My very long title</h3>
<h3>Another long title</h3>

If I wanted to shorten these titles using PHP or jQuery, how can I trim them to the nearest word and append an ellipsis? Is it possible to specify a character count?

<h3>My very long...</h3>
<h3>Another long...</h3>

Edit - How can I do this for each one of the headlines? I don't really have an idea as to how to pass each headline into a string...

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is easy using a PHP function. Look at this example:

function trim_text($input, $length) {

    // If the text is already shorter than the max length, then just return unedited text.
    if (strlen($input) <= $length) {
        return $input;
    }

    // Find the last space (between words we're assuming) after the max length.
    $last_space = strrpos(substr($input, 0, $length), ' ');
    // Trim
    $trimmed_text = substr($input, 0, $last_space);
    // Add ellipsis.
    $trimmed_text .= '...';

    return $trimmed_text;
}

You can then pass in text with a function like:

trim_text('My super long title', 10);

(I haven't tested this, but it should work perfectly.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...