Reputation: 35
I have below example
$game = "hello999hello888hello777last";
preg_match('/hello(.*?)last/', $game, $match);
The above code returns 999hello888hello777, what I need is to retrieve the value just before Last, i.e 777. So I need to read regular expression to read from right to left.
Upvotes: 3
Views: 2510
Reputation: 336208
Your problem is that although .*
matches reluctantly, i. e. as few characters as possible, it still starts matching right after hello
, and since it matches any characters, it will match right across "boundaries" (last
and hello
in your case).
Therefore you need to be more explicit about the fact that it's not legal to match across boundaries, and that's what lookahead assertions are for:
preg_match('/hello((?:(?!hello|last).)*)last(?!.*(?:hello|last)/', $game, $match);
Now the match between hello
and last
is prohibited from containing hello
and/or last
, and it's not allowed to have hello
or last
after the match.
Upvotes: 1
Reputation: 5050
This will return the last set of digits before the string last
$game = "hello999hello888hello777last";
preg_match('/hello(\d+)last$/', $game, $match);
print_r($match);
Output Example:
Array
(
[0] => hello777last
[1] => 777
)
So you would need $match[1];
for the 777 value
Upvotes: 2
Reputation: 6632
Why not just reverse the string? Use PHP's strrev and then just reverse your regular expression.
$game = "hello999hello888hello777last";
preg_match('/tsal(.*?)elloh/', strrev($game), $match);
Upvotes: 2
Reputation: 1943
$game = strrev($game);
How about that? :D
Then just reverse the regular expression ^__^
Upvotes: 4