2

I'm trying to use numeric literals with my array $test with preg_replace in PHP, there is what I got:

$test["a"] = "hey";

// Find a as $0
echo preg_replace("/[a-z]/", "Found:$0", "a")."\n";

// Can replace it by "hey"
echo preg_replace("/[a-z]/", $test['a'], "a")."\n";

// Can't replace it :/
echo preg_replace("/[a-z]/", $test["$0"], "a")."\n";

As you see, the last preg_replace function doesn't work, whereas the two others work fine... I tried a lot of times to include the $0 with various tricks, but nothing stills work... Can you help me, please?

Loïc
  • 33
  • 4

2 Answers2

2

You can use preg_replace_callback() :

echo preg_replace_callback("/[a-z]/", function ($b) use ($test) {
    return $test[$b[0]];
}, "a")."\n";

With more tests :

echo preg_replace_callback("/[a-z]/", function ($b) use ($test) {
    if (isset($b[0]) && isset($test[$b[0]]))
        return $test[$b[0]];
    return "";
}, "a")."\n";
Syscall
  • 19,327
  • 10
  • 37
  • 52
0

Your current use case does not require regex, you can (and should if possible) use strtr or str_replace depending on what the requirements are:

$test["a"] = "hey";
$test["b"] = "you";

echo strtr("a b", $test); //hey you

echo str_replace(array_keys($test), array_values($test), "a b"); //hey you

Refer to When to use strtr vs str_replace? on what the differences are.

apokryfos
  • 38,771
  • 9
  • 70
  • 114