How can I reuse the key value of the search parameter in the replace parameter in str_replace()?

StackOverflow https://stackoverflow.com/questions/23094889

  •  04-07-2023
  •  | 
  •  

Question

What would be the syntax to reuse the key value of the search parameter in the replace parameter, for example

$key = array($value1, $value2, …);
echo str_replace($key, "<span class='key'>$key</span>", $content);

The above will return an Array rather than a single array item.

Was it helpful?

Solution

You can also use preg_replace_callback. Str replace doesn't accept arguments in the replacement string.

$key = array($value1, $value2, …);
$regex = addslashes(implode('|', $key));
$content = preg_replace_callback(
  "/$regex/",
  function ($matches) {
    return '<span class="key">'.$matches[0].'</span>';
  },
  $content
);

bitWorking has a better answer though if you can make each value in the array it's own regular expression.

OTHER TIPS

Use preg_replace

$key = array('/a/', '/b/');
echo preg_replace($key, '<span class="key">$0</span>', 'a b');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top