Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 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 Reply

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...