正则表达式从结尾匹配

时间:2013-09-23 12:25:12

标签: php regex

你好我需要匹配一个来自end(从右到左)的字符串。例如,从字符串hello999hello888hello 777 最后我需要在最后一组{之间得到 777 {1}}和hello。从下面的代码中可以正常工作。

last

但是,我没有777,而是混合了符号数字和字母,假设例如来自字符串$game = "hello999hello888hello777last"; preg_match('/hello(\d+)last$/', $game, $match); print_r($match); ,我需要hello999hello888hello0string#@$@#anysymbols%@iwantlast

0string#@$@#anysymbols%@iwant

为什么上面的代码会重复$game = "hello999hello888hello0string#@$@#anysymbols%@iwantlast"; preg_match('/hello(.*?)last$/', $game, $match); print_r($match); 。从右到左读取正确的过程,然后是字符串反向方法。

注意:我想使用preg_match_all aswel.for匹配多个字符串。例如

999hello888hello0string#@$@#%#$%#$%#$%@iwant

必须返回$string = 'hello999hello888hello0string#@$@#anysymbols%@iwantlast hello999hello888hello02ndstring%@iwantlast'; preg_match_all('/.*hello(.*?)last$/', $string, $match); print_r($match); 0string#@$@#anysymbols%@iwant

2 个答案:

答案 0 :(得分: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

对于多行,只需删除$

答案 1 :(得分:2)

这个正则表达式会做你想要的(包括多次匹配):

/.*hello(.*)last/

工作示例:

$string = 'hello999hello888hello0string#@$@#anysymbols%@iwantlast

hello999hello888hello02ndstring%@iwantlast';

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

/**   

Output: 


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

*/
相关问题