简体   繁体   中英

Twig: How to remove twig tags from external string in PHP?

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM