Extracting all values between curly braces regex php

前端 未结 3 1437
醉酒成梦
醉酒成梦 2020-11-28 13:22

I have content in this form

$content =\"

This is a sample text where {123456} and {7894560} [\'These are samples\']{145789}

\";
3条回答
  •  萌比男神i
    2020-11-28 13:58

    Two compact solutions weren't mentioned:

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

    and

    {\K[^}]*(?=})
    

    These allow you to access the matches directly, without capture groups. For instance:

    $regex = '/{\K[^}]*(?=})/m';
    preg_match_all($regex, $yourstring, $matches);
    // See all matches
    print_r($matches[0]);
    

    Explanation

    • The (?<={) lookbehind asserts that what precedes is an opening brace.
    • In option 2, { matches the opening brace, then \K tells the engine to abandon what was matched so far. \K is available in Perl, PHP and R (which use the PCRE engine), and Ruby 2.0+
    • The [^}] negated character class represents one character that is not a closing brace,
    • and the * quantifier matches that zero or more times
    • The lookahead (?=}) asserts that what follows is a closing brace.

    Reference

    • Lookahead and Lookbehind Zero-Length Assertions
    • Mastering Lookahead and Lookbehind

提交回复
热议问题