Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple characters with multiple replacers [duplicate]

Tags:

regex

php

I have many calls like this throughout the code, escaping any backticks on the columns of a row.

htmlentities(str_replace("`", "``", $row['column']), ENT_QUOTES);

I made an addition, requiring the column to replace a #width ##. Since most of these calls happen inline an output, I would like to have a solution in a single line.

I was thinking conditional regex (preg_replace_callback), but is this the best way to achieve that? So what I need is: replace backticks with 2 backticks, and replace hashes with 2 hashes. (This is for escaping purposes).

like image 224
Johannes Avatar asked Feb 12 '26 19:02

Johannes


1 Answers

str_replace() supports array parameters:

// translation map:
$map = [
    '`' => '``',
    '#' => '##'
];

// what to replace:
$from = array_keys($map);

// replace by what:
$to   = array_values($map);

echo htmlentities(str_replace($from, $to, $row['column']), ENT_QUOTES);

In rare cases, that requires you to minify your code, you may try to use that:

echo htmlentities(str_replace([ '`', '#' ], [ '``', '##' ], $row['column']), ENT_QUOTES));
//                            ^             ^
//                        from what     by what
like image 82
BlitZ Avatar answered Feb 15 '26 09:02

BlitZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!