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
477 views
in Technique[技术] by (71.8m points)

php trim a string

I'm trying to build a function to trim a string is it's too long per my specifications.

Here's what I have:

function trim_me($s,$max) 
{
    if (strlen($s) > $max) 
    {
        $s = substr($s, 0, $max - 3) . '...';
    }
    return $s;
}

The above will trim a string if it's longer than the $max and will add a continuation...

I want to expand that function to handle multiple words. Currently it does what it does, but if I have a string say: How are you today? which is 18 characters long. If I run trim_me($s,10) it will show as How are yo..., which is not aesthetically pleasing. How can I make it so it adds a ... after the whole word. Say if I run trim_me($s,10) I want it to display How are you... adding the continuation AFTER the word. Any ideas?

I pretty much don't want to add a continuation in the middle of a word. But if the string has only one word, then the continuation can break the word then only.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

So, here's what you want:

<?php
// Original PHP code by Chirp Internet: www.chirp.com.au 
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break=".", $pad="...") { 
    // is $break present between $limit and the end of the string? 
    if(false !== ($breakpoint = strpos($string, $break, $limit))) { 
        if($breakpoint < strlen($string) - 1) { 
            $string = substr($string, 0, $breakpoint) . $pad; 
        } 
    } 
    return $string;
}
?>

Also, you can read more at http://www.the-art-of-web.com/php/truncate/


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

...