2013-03-08 47 views
1

我試圖獲取字符串中的最後幾個單詞。 爲此我使用這個詞:如何使用preg_match獲取字符串中的最後一個單詞

$string = "Hallo dies ist ein extrem langer Text den ich gern gekuerz haette, leider bin ich selbst zu doof dafür und mach hier einen test."; 

$pattern = '/[^ ]*$/'; 

preg_match($pattern, $string, $result); 

echo "<br>The last word is:------ ". $result[0] ." ---------<br>"; 

它工作正常。但我沒有進入前跑步。最後的樹詞。 我不知道如何改變模式。 感謝您提前提供任何幫助。

回答

1

這將做的工作

$pattern = '/(([^ ]*)\s+([^ ]*)\s+([^ ]*))$/'; 

Example

$pattern = '/((([^ ]*)[\s.]+){3})$/'; 

Example

+0

這是偉大的peterm,謝謝 – hamburger 2013-03-08 17:18:24

+0

我怎麼看你只是複製模式部分三次。 是否還有可能使用{3}等參數進行操作? – hamburger 2013-03-08 17:23:12

+0

@hamburger查看更新後的答案。 – peterm 2013-03-08 17:45:08

2

這可能會更好過在字符串中使用explode,這樣的事情:

$string = 'Hello, my name is Jordan Doyle'; 
$string_array = explode(' ', $string); 
echo end($string_array); 

輸出示例:

[email protected]:~# php example.php 
Doyle 

[email protected]:~# 

這裏有一個函數來獲取指定的行量...

<?php 
function get_last_words($amount, $string) 
{ 
    $string_array = explode(' ', $string); 

    return array_slice($string_array, count($string_array) - $amount); 
} 

$string = 'Hello, my name is Jordan Doyle'; 
var_dump(get_last_words(3, $string)); 

示例輸出:

[email protected]:~# php example.php 
array(3) { 
    [0]=> 
    string(2) "is" 
    [1]=> 
    string(6) "Jordan" 
    [2]=> 
    string(5) "Doyle" 
} 

[email protected]:~# 
+0

我正在使用這個: $ length = 3; $ shortStart = implode('',array_slice(str_word_count($ string,1),0,$ length)); 回聲「
縮短:------」。 $ shortStart。「---------
」; (str_word_count($ string,1),count(str_word_count($ string,1)) - $ length)); $ shortend = implode('',array_slice(str_word_count($ string, 回聲「
縮短:------」。 $縮短了。「---------
」; 它工作正常,但我現在正在尋找模式,以建立一個功能。 – hamburger 2013-03-08 17:04:37

+0

編輯我的文章,以包括這個給你。 – 2013-03-08 17:20:13

0

編輯

$patterns = '/\b[a-zA-Z]*\b/'; 

,並使用preg_match_all匹配所有出現

preg_match_all($patterns, $string, $result); 

    $string = "Hallo dies ist ein extrem langer Text den ich gern gekuerz haette, leider bin ich selbst zu doof daf&uuml;r und mach hier einen test."; 

preg_match_all($patterns, $string, $result); 

foreach($result[0] as $value){ 
    echo "$value "; 
} 



for($length = count($result[0]), $i = 1; $i < 4; $i++){ 
     $offset = $length - $i; 
     echo $result[0][$offset]; 
    } 

上面的代碼中提取最後3個字

+0

對不起,使用這種模式給出了這個: 最後一句話是:------聖。 --------- 這就是最後三個字母... – hamburger 2013-03-08 16:59:36

+0

對不起。 。 。我誤解了這個問題。 。 。 。您可以使用\ b來匹配單詞邊界並從結果數組中檢索任意數量的單詞 – palerdot 2013-03-08 17:25:13

+0

這隻會返回第一個單詞.. 並且不匹配該行中的所有單詞。 – hamburger 2013-03-08 17:34:17

0

這也可能是最好使用爆炸的字符串,像這樣:

<?php 
$cate = 'category-node-25'; 
$cateId = explode('-', $cate); 
echo end($cateId); 
?> 

輸出 - > 25.

相關問題