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.

    评论

报告相同问题?