Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match from end

Tags:

regex

php

Hello i need to match an string from end (right to left).For example From the string hello999hello888hello777last i need to get 777 between last set of hello and last .Which works correctly from below code.

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

But , instead of 777 , i have mixture of symbols numbers and alphabets , suppose for example From string hello999hello888hello0string#@$@#anysymbols%@iwantlast i need to take 0string#@$@#anysymbols%@iwant.

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

why is that above code returing 999hello888hello0string#@$@#%#$%#$%#$%@iwant .What is the correct procedure to read from right to left other then string reverse method.

Note : i want to match multiple string using preg_match_all aswel.for example

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

hello999hello888hello02ndstring%@iwantlast';

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

which must return 0string#@$@#anysymbols%@iwant and 02ndstring%@iwant

like image 279
Vishnu Avatar asked May 13 '26 23:05

Vishnu


1 Answers

Try changing your regex like this:

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

Explanation:

.*     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

The ? is actually unneccessary, because if you're anchoring to the end you want the last last anyway. Remove the $ if you want to match something like helloMatch this textlastDon't match this.

For multiline, just remove the $ as well.

like image 76
tckmn Avatar answered May 15 '26 13:05

tckmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!