PHP - split a string using str_word_count as opposed to preg_replace

296 Views Asked by At

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

There are 3 best solutions below

1
On

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.

0
On

You could go for the first space after a number of characters like this...

<?php
$string = "A long title is not great for the world to read.";
$splitPosition = strpos($string, " ", 10);
print "<h1>" . substr($string, 0, $splitPosition) . "<span>" . substr($string, $splitPosition) . "</span></h1>";
?>
0
On

This is my two cents. mb_substr function from php manual.

    $string = "A long title is not great for the world to read";
    echo "<h1>".mb_substr($string,0,13);."<span>".mb_substr($string,13,strlen($string))."</span></h1>";