dss67853 2018-04-26 15:08
浏览 60
已采纳

拆分字符串,按字数读取更多

I need a split string with 2 divs, by the first div with 20 words and last div with rest of words to make read more link with javascript.

At the moment I have only character count limit.

How can I do word splitting?

if ( $term && ! empty( $term->description ) ) {
            $first = substr($term->description, 0, 400);
            $rest = substr($term->description, 400);
            echo '<div class="term-description"><div class="first-letter">'.$first.'</div><div class="last-letter">'.$rest.'</div></div>';
        }
  • 写回答

2条回答 默认 最新

  • dsvs50005 2018-04-26 15:18
    关注

    This code does the trick:

    <?php
    
    function SplitStringToParts($sourceInput, &$first, &$rest, $countWordsInFirst = 20)
    {
        $arr_exploded = explode(" ", $sourceInput);
    
        $arr_part1 = array_slice($arr_exploded, 0, $countWordsInFirst);
        $arr_part2 = array_slice($arr_exploded, $countWordsInFirst);
    
        $first = implode(" ",$arr_part1);
        $rest = implode(" ",$arr_part2);    
    }
    
    $str = "str1 str2 str3 str4 str5 str6 str7 str8 str9 str10 str11 str12 str13 str14 str15 str16 str17 str18 str19 str20 str21 str22 str23 str24";
    
    SplitStringToParts($str,$first,$rest,20);
    
    echo $first."<br>";
    echo $rest."<br>";
    

    Output is:

    str1 str2 str3 str4 str5 str6 str7 str8 str9 str10 str11 str12 str13 str14 str15 str16 str17 str18 str19 str20
    str21 str22 str23 str24
    

    Use SplitStringToParts function. In your case you should call it as: SplitStringToParts($term->description, $first, $rest, 20);

    After it $first, $rest will keep your result

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?