0

OK, that's what I need :

  • Get all entries formatted like %%something%%, as given by the regex /%%([A-Za-z0-9\-]+)%%/i
  • Replace all instances with values from a table, given the index something.

E.g.

Replace %%something%% with $mytable['something'], etc.


If it was a regular replacement, I would definitely go for preg_replace, or even create an array of possible replacements... But what if I want to make it a bit more flexible...

Ideally, I'd want something like preg_replace($regex, $mytable["$1"], $str);, but obviously it doesn't look ok...


How should I go about this?

7
  • 4
    You are looking for preg_replace_callback. Commented May 17, 2013 at 9:39
  • Though I am not a PHP guy, but you may try adding global hook g in your regex, e.g. /%%([A-Za-z0-9\-]+)%%/gi Commented May 17, 2013 at 9:40
  • 1
    @Dr.Kameleon: No need really. If you want to give credit, just upvote on that other question. Cheers! Commented May 17, 2013 at 9:42
  • 1
    @Jon Na sai kala. (= nobody is gonna understand that. lol) Commented May 17, 2013 at 9:43
  • 1
    If you use the [A-Za-z0-9-] class, you don't need to put the i modifier Commented May 17, 2013 at 9:46

1 Answer 1

2

Code:

<?php

$myTable = array(
    'one' => '1!',
    'two' => '2!',
);

$str = '%%one%% %%two%% %%three%%';

$str = preg_replace_callback(
    '@%%(.*?)%%@',
    function ($matches) use ($myTable) {
        if (isset($myTable[$matches[1]]))
            return $myTable[$matches[1]];
        else
            return $matches[0];
    },
    $str
);

echo $str;

Result:

1! 2! %%three%%

if you don't want to tell upper from lower,

<?php

$myTable = array(
    'onE' => '1!',
    'Two' => '2!',
);

$str = '%%oNe%% %%twO%% %%three%%';

$str = preg_replace_callback(
    '@%%(.*?)%%@',
    function ($matches) use ($myTable) {
        $flipped = array_flip($myTable);
        foreach ($flipped as $v => $k) {
            if (!strcasecmp($k, $matches[1]))
                return $v;
        }
        return $matches[1];
    },
    $str
);

echo $str;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.