0

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.

Eleandro Duzentos
  • 1,370
  • 18
  • 36
  • Possible duplicate of [Getting the current index in preg\_replace\_callback?](https://stackoverflow.com/questions/8484062/getting-the-current-index-in-preg-replace-callback) – RST May 25 '17 at 10:34
  • @RST: This has nothing to do with the question. – Toto May 25 '17 at 10:37

2 Answers2

1

Don't use an array of regexps, use a single regexp with alternatives and capture groups. Then you can see which capture group is not empty.

$regex = '/(def)|(ghi)|(abc)/';
$string = preg_replace_callback($regex, function($match) {
    for ($i = 1; $i < count($match); $i++) {
        if ($match[$i]) {
            return strtoupper($match[$i]) . " was matched by pattern " . $i-1;
        }
    }
}, $string);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

@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
)
revo
  • 47,783
  • 14
  • 74
  • 117