Given the string {{esc}}"Content"{{/esc}} ... {{esc}}"More content"{{/esc}}
I would like to output \"Content\" ... \"More content\"
e.g., I am trying to escape the quotes inside a string. (This is a contrived example, though, so an answer with something like 'just use this library to do it' would be unhelpful.)
Here is my current solution:
return preg_replace_callback(
'/{{esc}}(.*?){{\/esc}}/',
function($m) {
return str_replace('"', '\\"', $m[1]);
},
$text
);
As you can see, I need to say $m[1]
, because a print_r
reveals that $m
looks like this:
Array
(
[0] => {{esc}}"Content"{{/esc}}
[1] => "Content"
)
or, for the second match,
Array
(
[0] => {{esc}}"More content"{{/esc}}
[1] => "More content"
)
My question is: why does my regex cause $m
to be an array? Is there any way I can get the result of $m[1]
as just a single variable $m
?