2013-09-23 49 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