Regex - How to replace the last 3 words of a string with PHP

后端 未结 3 360
独厮守ぢ
独厮守ぢ 2021-01-26 20:03

Trying to wrap the last 3 words in a tag

$str = \'Lorem ipsum dolor sit amet\';
$h2 = preg_replace(\'/^(?:\\w+\\s\\w+)(\\s\\w+)+/\', \'         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-26 20:42

    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) . '';
    }
    

提交回复
热议问题