简体   繁体   English

正则表达式-如何用PHP替换字符串的最后3个单词

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

Trying to wrap the last 3 words in a <span> tag 尝试将最后3个单词包装在<span>标记中

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

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. Sabuj Hassan还将数字和_视为单词的一部分,因此请在有意义的情况下使用它。

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);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM