简体   繁体   English

树枝:如何从PHP的外部字符串中删除树枝标签?

[英]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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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