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?
You could use
substr
to get your first part and then useltrim
to trim it from our main string. Or you could usesubstr
twice for the first and last part of your string.