Trying to wrap the last 3 words in a tag
$str = \'Lorem ipsum dolor sit amet\';
$h2 = preg_replace(\'/^(?:\\w+\\s\\w+)(\\s\\w+)+/\', \'
There is no reason to use regex here at all if you define words as being bounded by a single space. Instead you can use basic string manipulation to get the desired result.
$str = ...; // your input string
$words_with_offsets_in_key = str_word_count($str, 2);
$word_count = count($word_offsets);
if($word_count >= 3) {
// we have at least 3 words
// find offset of word three from end of array of words
// grab third item from end of array
$third_word_from_end = array_slice($words_with_offsets_in_key, $word_count - 3, 1);
// inspect its key for offset value in original string
$offset = key($third_word_from_end);
// insert span into string
$str = substr_replace ( $str , '' , $offset, 0) . '';
}