173

I want to find substring of the string or check if there is no such substring using Twig. On the words, I need analogue of 'strstr' or 'strpos' in php. I googled and searched this issue in stackoverflow but nothing found. Does someone know how to solve this problem?

4
  • 2
    Nothing found, really? When I google Find substring in the string in TWIG, I get a first hit that looks really good. I don't think it's going to get any better than that.
    – Pekka
    Oct 22, 2012 at 8:10
  • Please follow the ask advice you needed to confirm before posting any question. Keep in mind that only you want something and you ask yourself how it is programmed does not qualify as a programming question per-se.
    – hakre
    Oct 22, 2012 at 8:13
  • Pekka, thanks for your link but it isn't exactly what i found. strstr and strpos lets find positions of substring in the string or return false if there is no such substring. It is not similar with strpos. Oct 22, 2012 at 8:22
  • 1
    If you don't find what you want, you can always do it yourself.
    – Maerlyn
    Oct 22, 2012 at 9:19

1 Answer 1

433

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}
7
  • 3
    Is it possible to use this inside an if statement?
    – TeaCupApp
    Oct 28, 2012 at 0:36
  • 8
    Yes, indeed, you can !
    – Flo Schild
    Apr 4, 2014 at 13:10
  • 7
    Great :) I used it to figure out the current route: <li class="{% if 'gew_team_default_' in app.request.get('_route') %}active{% endif %}"> Aug 28, 2014 at 14:11
  • 1
    Is it affected by slashes or special characters? I am trying to do is find /some-link in some-doma.in/some-link... Sep 7, 2017 at 16:57
  • 17
    Just for completeness, the syntax for testing whether a substring is not present is: {% if 'needle' not in haystack %}
    – geekbrit
    Apr 17, 2018 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.