Reputation: 19366
Do not ask me why, but I have strings from an external source which are interpreted and I want to strip or escape all possible twig tags from it (external user should not be allowed to use twig).
Example:
<h1>{{ pageTitle }}</h1>
<div class="row">
{% for product in products %}
<span class="mep"></span>
{% endfor %}
</div>
Desired result:
<h1></h1>
<div class="row">
<span class="mep"></span>
</div>
What is the best way to achieve this?
Upvotes: 0
Views: 787
Reputation: 4124
You can escape the Twig tags (as described here) using {{ '{{' }}
, {{ '}}' }}
, {{ '{%' }}
and {{ '%}' }}
.
$input = '<h1>{{ pageTitle }}</h1>
<div class="row">
{% for product in products %}
<span class="mep"></span>
{% endfor %}
</div>';
$search = "/({{|}}|{%|%})/";
$replace = "{{ '$1' }}";
echo preg_replace($search, $replace, $input);
Upvotes: 1
Reputation: 19366
My regex solution (better solution still welcome):
$input = '<h1>{{ pageTitle }}</h1>
<div class="row">
{% for product in products %}
<span class="mep"></span>
{% endfor %}
</div>';
$search = '/({{.+}})|({%.+%})/si';
$replace = '';
echo preg_replace($input, $search, $replace);
Upvotes: 0