2

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

1
  • 2
    Remember that you can single line everything by making a function do the work for you. Commented Sep 1, 2014 at 7:33

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

12 Comments

he said in single row :p
@GeorgeGarchagudashvili I believe it would be not readable, so I strongly suggest to write readable code.
Sometimes there comes situation you need just a single row, not wasting things for unreadable 'readable'
@GeorgeGarchagudashvili sometimes. However, it might be "good" to think about future readers not to cry by blood, by "deminifying" source codes or templates.
While I agree, that this would be the proper way of making readable code, it's not applicable with the code I have. There are a lot of those calls throughout the code, and I just needed a replacement-string for my IDE.
|
3

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

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

Comments

3

if someone would prefer to use a regular expression:

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

Comments

2

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.