2013-09-23 128 views
3

你好,我需要匹配端(從右到左)。例如一個字符串從字符串hello999hello888hello 最後我需要得到最後一組hellolast。其中間從下面的代碼正確工作。正則表達式從最終匹配

$game = "hello999hello888hello777last"; 
preg_match('/hello(\d+)last$/', $game, $match); 
print_r($match); 

但是,相反的777,我有符號號碼和字母的混合物,假設例如從字符串hello999hello888hello0string#@[email protected]#anysymbols%@iwantlast我需要0string#@[email protected]#anysymbols%@iwant

$game = "hello999hello888hello0string#@[email protected]#anysymbols%@iwantlast"; 
preg_match('/hello(.*?)last$/', $game, $match); 
print_r($match); 

這是爲什麼上面的代碼returing 999hello888hello0string#@[email protected]#%#$%#$%#$%@iwant何爲從右到讀取到左其他然後串反向方法的正確步驟。

注:我想用preg_match_all aswel.for例如

$string = 'hello999hello888hello0string#@[email protected]#anysymbols%@iwantlast 

hello999hello888hello02ndstring%@iwantlast'; 

preg_match_all('/.*hello(.*?)last$/', $string, $match); 
print_r($match); 

它必須返回0string#@[email protected]#anysymbols%@iwant02ndstring%@iwant

+0

提示:*是貪婪的,這意味着它_eats_儘可能它可以在一個匹配的正則表達式中 – Jost

+0

爲什麼你這樣拆分字符串?在我看來,這是一個XY問題:http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem –

回答

3

試着改變你的正則表達式這樣來匹配多個字符串:

/.*hello(.*?)last$/ 

說明:

.*  eat everything before the last 'hello' (it's greedy) 
hello eat the last hello 
(.*?) capture the string you want 
last and finally, stop at 'last' 
$  anchor to end 

?實際上是不必要的,因爲如果你要堅持到最後你想要最後的last無論如何。如果要匹配helloMatch this textlastDon't match this之類的內容,請刪除$

對於多行,只需刪除$以及。

+0

謝謝。但它沒有工作,以匹配字符串中的多個匹配...請看到我編輯的問題。 – Vishnu

+0

@VishnuVishwa所以,你想匹配一個換行符之前的最後一個hello,到'last \ n'?我現在正在編輯我的答案 – Doorknob

+0

如果最後有字符,將不起作用。 –

2

此正則表達式會做你想要的(包括匹配多次)什麼:

/.*hello(.*)last/ 

工作例如:

$string = 'hello999hello888hello0string#@[email protected]#anysymbols%@iwantlast 

hello999hello888hello02ndstring%@iwantlast'; 

preg_match_all('/.*hello(.*)last/', $string, $matches); 
var_dump($matches) 

/** 

Output: 


array(2) { 
    [0]=> 
    array(2) { 
    [0]=> 
    string(54) "hello999hello888hello0string#@[email protected]#anysymbols%@iwantlast" 
    [1]=> 
    string(42) "hello999hello888hello02ndstring%@iwantlast" 
    } 
    [1]=> 
    array(2) { 
    [0]=> 
    string(29) "0string#@[email protected]#anysymbols%@iwant" 
    [1]=> 
    string(17) "02ndstring%@iwant" 
    } 
} 

*/ 
+0

謝謝:)工作,但首先回答Darknoob.anyway +1 :) – Vishnu

+0

這仍然會匹配'helloSome文本到matchlastOh否,額外文本結束後' – Doorknob

+0

你是什麼意思門把手?你也回答相同 – Vishnu