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

substring - How to capture complete words using substr() in PHP, limit by word?

When I use substr($string,0,100), it gives first 100 characters. Sometimes it left the last word incomplete. That looks odd. Can I do limit by word rather than char?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you just count the words the resulting sting could still be very long as a single "word" might have 30 characters or more. I would suggest instead truncating the text to 100 characters, except if this causes a word to be truncated then you should also remove the truncated part of the word. This is covered by this related question:

How to Truncate a string in PHP to the word closest to a certain number of characters?

Using wordwrap

$your_desired_width = 100;
if (strlen($string) > $your_desired_width)
{
    $string = wordwrap($string, 100);
    $i = strpos($string, "
");
    if ($i) {
        $string = substr($string, 0, $i);
    }
}

This is a modified versions of the answer here. if the input text could be very long you can add this line before the call to wordwrap to avoid wordwrap having to parse the entire text:

$string = substr($string, 0, 101);

Using a regular expression (Source)

$string = preg_replace('/s+?(S+)?$/', '', substr($string, 0, 100));

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

...