如何在PHP中使用substr()捕获完整的单词,逐字逐句地限制? [英] How to capture complete words using substr() in PHP, limit by word?

查看:99
本文介绍了如何在PHP中使用substr()捕获完整的单词,逐字逐句地限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用substr($string,0,100)时,它会给出前100个字符.有时,它使最后一个单词不完整.看起来很奇怪.我可以按单词而不是字符进行限制吗?

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?

推荐答案

如果仅对单词进行计数,则由于单个单词"可能包含30个或更多字符,结果字符串仍可能很长.我建议将文本截断为100个字符,除非这会导致单词被截断,否则您还应该删除该单词的截断部分.这个相关问题涵盖了这一点:

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, "\n");
    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);

使用正则表达式 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆