Search code examples
phpregexpreg-replace-callback

How to get the pattern that matched a string based on the string order


Suppose we have the follow array:

$regexList = ['/def/', '/ghi/', '/abc/'];

and the string bellow:

$string = '

{{abc}}
{{def}}
{{ghi}}

';

The idea is to go through the string from top to bottom and relying on the list of regular expressions, find the result and replace it with the content in uppercase with the pattern that matched the occurrence based on the string order no matter in what order the regexList array is.

So, that's my desired output:

  • ABC was matched by: /abc/;
  • DEF was matched by: /def/;
  • GHI was matched by: /ghi/;

or at leats

  • ABC was matched by pattern: 2;
  • DEF was matched by: 0;
  • GHI was matched by: 1;

This the the code i've trying:

$regexList = ['/def/', '/ghi/', '/abc/'];

$string = '

abc
def
ghi

';

$string = preg_replace_callback($regexList, function($match){
  return strtoupper($match[0]);
}, $string);

echo '<pre>';
var_dump($string);

This output just:

string(15) "

ABC
DEF
GHI

"

How can i get the offset or the pattern that match these strings in the $string order (top to bottom)? Thank you.


Solution

  • @Barmar is right but I'm going to modify it a little:

    $order = [];
    
    $string = preg_replace_callback('/(def)|(ghi)|(abc)/', function($match) use (&$order) {
        end($match);
        $order[key($match)] = current($match);
        return strtoupper($match[0]);
    }, $string);
    
    print_r($order);
    

    Output:

    Array
    (
        [3] => abc
        [1] => def
        [2] => ghi
    )