Twig 中的子字符串计数

Jak*_*e N 6 substring count twig

我想在 Twig 中使用substr_count,是否已经存在任何东西?我想做这样的事情;

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

echo substr_count($text, 'is'); // 2
Run Code Online (Sandbox Code Playgroud)

我可以进行扩展,但似乎这可能是我已经错过的内置功能。

Rus*_*per 7

这个怎么样?

{%set count = text|split('is')|length-1 %}
Run Code Online (Sandbox Code Playgroud)


Jak*_*e N 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

并且在services.yml

app.twig_extension.substr_count_extension:
    class: AppBundle\Twig\SubStrCountExtension
    tags:
        - { name: twig.extension }
Run Code Online (Sandbox Code Playgroud)