dongye9182 2010-08-21 16:04
浏览 90
已采纳

如何使用PHP中的substr()捕获完整的单词,按字词限制?

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?

  • 写回答

7条回答 默认 最新

  • dongsashe6006 2010-08-21 16:08
    关注

    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));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助