How to get the shortest rather than longest possible regex match with preg_match()

前端 未结 3 2171
臣服心动
臣服心动 2020-12-03 16:00

I have string similar to this one:

{{something1}} something2 {{something3}} something4

How can I match only \"something1\" using the

相关标签:
3条回答
  • 2020-12-03 16:05

    a full answer - if our $var is:

    STARTT 
    FIRST KKK
    SECOND KKK
    

    1) In case we use:

    $var = preg_replace('/STARTT(.*)KKK/', 'REPLACED-STRING', $var);
    

    it will change everything from the STARTT to last KKK and Result will be:

    REPLACED-STRING
    

    2) In case we use:

    $var = preg_replace('/STARTT(.*?)KKK/', 'REPLACED-STRING', $var);
    

    Result will be:

    REPLACED-STRING 
    SECOND KKK
    
    0 讨论(0)
  • 2020-12-03 16:22

    Use non greedy modifier ? :

    preg_match("/\{\{(.*?)\}\}/si",$content,$matches);
                 here --^
    
    0 讨论(0)
  • 2020-12-03 16:29

    Try this:

    preg_match('|{{([^}]+)}}|si', $content, $matches);
    
    echo $matches[1];
    
    0 讨论(0)
提交回复
热议问题