3

您好,我需要从结尾(从右到左)匹配一个字符串。例如,从字符串 hello999hello888hello 777 last 我需要在最后一组和. 之间获取777。从下面的代码中可以正常工作。hellolast

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

但是,而不是 777,我混合了符号数字和字母,例如我需要从字符串中获取。hello999hello888hello0string#@$@#anysymbols%@iwantlast0string#@$@#anysymbols%@iwant

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

为什么上面的代码会返回999hello888hello0string#@$@#%#$%#$%#$%@iwant。除了字符串反转方法之外,从右到左读取的正确程序是什么。

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

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

hello999hello888hello02ndstring%@iwantlast';

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

必须返回0string#@$@#anysymbols%@iwant02ndstring%@iwant

4

2 回答 2

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.

对于多行,只需删除$

于 2013-09-23T12:28:42.710 回答
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"
  }
}

*/
于 2013-09-23T12:36:14.397 回答