169

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
user1440167
  • 1,913
  • 2
  • 12
  • 12
  • 2
    Nothing found, really? When I google `Find substring in the string in TWIG`, I get a [first hit](https://groups.google.com/forum/?fromgroups=#!topic/twig-users/50KrckEAkkA) that looks really good. I don't think it's going to get any better than that. – Pekka Oct 22 '12 at 08:10
  • Please follow the [ask advice](http://stackoverflow.com/questions/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 '12 at 08: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. – user1440167 Oct 22 '12 at 08:22
  • 1
    If you don't find what you want, you can always [do it yourself](http://twig.sensiolabs.org/doc/advanced.html). – Maerlyn Oct 22 '12 at 09:19

1 Answers1

423

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' }}
Dalin
  • 3,012
  • 1
  • 21
  • 21
HamZa
  • 14,671
  • 11
  • 54
  • 75
  • @TobiasOberrauch so did I ; you can also use `app.request.pathinfo` as comparison :) – neemzy Dec 29 '14 at 11:26
  • 1
    Is it affected by slashes or special characters? I am trying to do is find `/some-link` in `some-doma.in/some-link`... – Vishal Kumar Sahu Sep 07 '17 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 '18 at 13:00
  • 1
    {%- if "☑" in output -%} ... does not work for me when output is set to ☑
    ()
    – ñull Apr 18 '19 at 11:04