如何使用 Twig 执行 RegEx? [英] How to perform RegEx using Twig?
本文介绍了如何使用 Twig 执行 RegEx?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以对树枝中的字符串进行正则表达式?
Is it possible to regex on a string in twig?
我的字符串是
<a class="twitter-timeline" data-dnt="true" href="https://twitter.com/example" data-widget-id="2374937989837">Tweets by @example</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
我只想获取
data-widget-id="2374937989837"
在我的模板中.
字符串输出为{{ this.theme.twitter }}
The string is outputted as {{ this.theme.twitter }}
我有这个搜索的正则表达式
I have my regex for this search as
id="\d+(\.\d+)*(,\d+)?"
推荐答案
为 Twig 编写自定义过滤器:
Write a custom filter for Twig :
<?php
$filter = new Twig_SimpleFilter('data_widget_id', function ($value) {
$matches;
if (preg_match('#data-widget-id="\d+(\.\d+)*(,\d+)?"#', $str, $matches)) return $matches[0];
return $value;
});
$twig = new Twig_Environment($loader);
$twig->addFilter($filter);
并在您的模板中使用它:
And use it in your template :
{{ this.theme.twitter | data_widget_id }}
这篇关于如何使用 Twig 执行 RegEx?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文