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

后端 未结 3 358
独厮守ぢ
独厮守ぢ 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 , '<span>' , $offset, 0) . '</span>';
    }
    
    0 讨论(0)
  • 2021-01-26 20:54

    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.

    0 讨论(0)
  • 2021-01-26 20:54

    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);
    
    0 讨论(0)
提交回复
热议问题