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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With