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

后端 未结 3 407
独厮守ぢ
独厮守ぢ 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: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', '$1', $str);
    
    echo $h2;
    

    If you want any non-whitespace considered a word then:

    $h2 = preg_replace('/(\S+ \S+ \S+)$/', '$1', $str);
    

提交回复
热议问题