簡體   English   中英

正則表達式-如何用PHP替換字符串的最后3個單詞

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

嘗試將最后3個單詞包裝在<span>標記中

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

這里是:

$h2 = preg_replace('/(\w+\s\w+\s\w+)$/', '<span>$1</span>', $str);

由於它的最后三個詞,所以使左側(從開始)開放以進行匹配。

Sabuj Hassan還將數字和_視為單詞的一部分,因此請在有意義的情況下使用它。

假設“單詞”是由空格分隔的字母

$str = 'Lorem ipsum dolor sit amet';
$h2 = preg_replace('/([a-z]+ [a-z]+ [a-z]+)$/i', '<span>$1</span>', $str);

echo $h2;

如果您想將任何非空格視為一個單詞,則:

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

如果將單詞定義為由單個空格限制,則完全沒有理由在此處使用正則表達式。 相反,您可以使用基本的字符串操作來獲得所需的結果。

$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