Johannes
Johannes

Reputation: 1329

Replace multiple characters with multiple replacers

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).

Upvotes: 2

Views: 304

Answers (4)

Aprillion
Aprillion

Reputation: 22322

if someone would prefer to use a regular expression:

preg_replace("/`|#/", "$0$0")

Upvotes: 3

BlitZ
BlitZ

Reputation: 12168

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

Upvotes: 4

Justinas
Justinas

Reputation: 43479

As stated in documentation of str_replace, you can use can use arrays:

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

Upvotes: 3

George G
George G

Reputation: 7695

It's easy, just use arrays as params for str_replace

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

Upvotes: 2

Related Questions