Twig中的子串数

时间:2016-07-04 09:51:07

标签: count twig substring

我希望在Twig中使用substr_count,是否已存在任何问题?我想做这样的事情;

<?php
$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2

我可以做一个扩展,但似乎这可能是我已经错过的内置。

4 个答案:

答案 0 :(得分:2)

这个怎么样?

{%set count = text|split('is')|length-1 %}

答案 1 :(得分:1)

这在Twig functionsfilters列表中不存在。

您必须编写自己的自定义函数/过滤器或尝试package(注意;我从未使用过这个软件包,因此无法对其进行评论,但是在Google搜索结果的第一页上)。

答案 2 :(得分:0)

我去了扩展

namespace AppBundle\Twig;

class SubStrCountExtension extends \Twig_Extension
{
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('substr_count', array($this, 'substr_count')),
        );
    }

    public function getName()
    {
        return 'substr_count_extension';
    }

    public function substr_count($str, $char)
    {
        return substr_count($str, $char);
    }
}

并在services.yml

app.twig_extension.substr_count_extension:
    class: AppBundle\Twig\SubStrCountExtension
    tags:
        - { name: twig.extension }

答案 3 :(得分:0)

我在Symfony 3.2.8中使用解决方案,但在描述中没有说这段代码应该在里面:服务 如果您没有显示此错误: 没有扩展能够加载.....的配置。

此代码应位于服务内,这是正确的:

services:

app.twig_extension.substr_count_extension:
    class: AppBundle\Twig\SubStrCountExtension
    tags:
        - { name: twig.extension }

最后,正确使用树枝是:

tu placa es: {{substr_count(datos.picoyplaca,4)}}

此致