Search code examples
phpregexpreg-match

Match curly brace wrapped characters in a slash delimited string


I'm trying to match a substring which contains no curly braces or forward slashes AND is wrapped by curly braces THEN wrapped by delimiting forward slashes.

Pseudocode: /{ any string not contain "/" and "{" and "}" inside }/

My test string /a/{bb}/{d{b}}/{as}df}/b{cb}/a{sdfas/dsgf}

My failed pattern: \/\{((?!\/).)*\}\/

My failed result:

array(2)
    =>  array(2)
        =>  /{bb}/
        =>  /{as}df}/
    )
    =>  array(2)
        =>  b
        =>  f
    )
)

I want it to only match /{bb}/ and isolate bb.


Solution

  • You can try this mate

    (?<=\/){[^\/{}]*?}(?=\/)
    

    Explanation

    • (?<=\/) - Positive look behind. Matches /
    • { - Matches {.
    • [^\/{}]*? - Matches everything except { and } and / zero or more time ( lazy mode ).
    • (?=\/) - Matches /.

    You can use this too \/({[^\/{}]*?})\/

    Demo