簡體   English   中英

如何從字符串中提取最后4個單詞?

[英]How to extract the last 4 words from a string?

我想從字符串中提取最后4個單詞作為一個單獨的塊。

例如,如果我有:

"Are You Looking For The Best Website Review"

我想將最后四個詞記為:

"The Best Website Review"

我只有基本的編碼知識,並且嘗試過在該論壇中可以找到的所有變體。

我最接近的是通過使用Rick Kuipers的建議( 如何獲取字符串的最后一個單詞 ),但這給了我這些單詞作為單獨的值。

$split = explode(" ", $str);

echo $split[count($split)-4];
echo $split[count($split)-3];
echo $split[count($split)-2];
echo $split[count($split)-1];

我的編碼知識有限,因此任何建議將不勝感激。

只需將str_word_countarray_splice一起使用,如下所示

$str = "Are You Looking For The Best Website Review";
$arr = str_word_count($str,1);
echo implode(' ',array_splice($arr,-4));

編輯

如果你的文本中包含Are-You-Looking-For-The-Best-Website-Review hiphen的,你可以使用str_replace等作為

$arr = str_word_count(str_replace('-',' ',$str),1);
echo implode(' ',array_splice($arr,-4));

演示

您可以為此使用簡單的正則表達式:

<?php

$subject = "Are You Looking For The Best Website Review";
$pattern = '/(\w+\s+\w+\s+\w+\s+\w+)\s*$/u';
preg_match($pattern, $subject, $tokens);

var_dump($tokens[0]);

輸出為:

string(23) "The Best Website Review"

這還具有一個優點,即單詞之間的空格的類型和數量無關緊要,並且忽略了字符串末尾的空格。


編輯:考慮到您對@Uchiha發布的答案的評論,這是模式的一種變體,它顯示了如何輕松匹配以空格分隔的其他字符分隔的單詞:

$pattern = '/(\w+[-\s]+\w+[-\s]+\w+[-\s]+\w+)\s*$/u';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM