Extracting all values between curly braces regex php

前端 未结 3 1417
醉酒成梦
醉酒成梦 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条回答
  • 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
    0 讨论(0)
  • 2020-11-28 14:10

    Do like this...

    <?php
    $content ="<p>This is a sample text where {123456} and {7894560} ['These are samples']{145789}</p>";
    preg_match_all('/{(.*?)}/', $content, $matches);
    print_r(array_map('intval',$matches[1]));
    

    OUTPUT :

    Array
    (
        [0] => 123456
        [1] => 7894560
        [2] => 145789
    )
    
    0 讨论(0)
  • 2020-11-28 14:19

    DEMO :https://eval.in/84197

    $content ="<p>This is a sample text where {123456} and {7894560} ['These are samples']{145789}</p>";
    preg_match_all('/{(.*?)}/', $content, $matches);
    foreach ($matches[1] as $a ){
    echo $a." ";
    }
    

    Output:

    123456 7894560 145789 
    
    0 讨论(0)
提交回复
热议问题