douzangdang2225 2015-06-15 22:14
浏览 33

PHP - 使用str_word_count而不是preg_replace拆分字符串

I'm trying to split long strings into 2 seperate pieces depending on varying word counts (some strings i would like split at 2 words, maybe other ones at 4, etc.) so that I can wrap the second split with a tag.

For example:

<?php $string = 'A long title is not great for the world to read";<?php>
<h1><?php echo $string;?></h1>

However, would prefer the output to be:

<h1>A long title <span>is not great for the world to read</span></h1>

I've almost successfully used this method, but I was having problems with the regex throwing fits when there were quotations or apostrophes in the string and figured maybe it's easier to just use str_word_count as it's also less taxing on the server:

function get_snippet($str, $wordCount) {
    $arr = preg_split(
        '/(?<=\w)\b/', 
        $str, 
        $wordCount*2+1, 
        PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
    );

    $first = implode('', array_slice($arr, 0, $wordCount));
    $last = implode('', array_slice($arr, $wordCount));

    return $first.'<span>'.$last.'</span>';
}

<h1>
    <?php $string = get_the_title(); echo get_snippet($string, 3);?>
</h1>

This code was modified from here: How to select first 10 words of a sentence?

  • 写回答

3条回答 默认 最新

  • dongshetao1814 2015-06-15 22:22
    关注

    You could use substr to get your first part and then use ltrim to trim it from our main string. Or you could use substr twice for the first and last part of your string.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)