Vishnu
Vishnu

Reputation: 2452

Regular expression to match from end

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

Upvotes: 3

Views: 200

Answers (2)

tckmn
tckmn

Reputation: 59273

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.

Upvotes: 3

Steven
Steven

Reputation: 6148

This regex will do what you want (including matching multiple times):

/.*hello(.*)last/

Working example:

$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"
  }
}

*/

Upvotes: 2

Related Questions