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 , '<span>' , $offset, 0) . '</span>';
}
Here it is:
$h2 = preg_replace('/(\w+\s\w+\s\w+)$/', '<span>$1</span>', $str);
Since its last three words, so make the left side(from begin) as open to have the match.
Sabuj Hassan's treats numbers and _ as being part of a word as well, so use that if it makes sense.
Assuming "words" are letters delimited by a space:
$str = 'Lorem ipsum dolor sit amet';
$h2 = preg_replace('/([a-z]+ [a-z]+ [a-z]+)$/i', '<span>$1</span>', $str);
echo $h2;
If you want any non-whitespace considered a word then:
$h2 = preg_replace('/(\S+ \S+ \S+)$/', '<span>$1</span>', $str);