Regex extract string between 2 curly braces

后端 未结 5 1873
梦如初夏
梦如初夏 2020-12-11 23:20

I have the following short codes:

Dear {{name}},

You are being invited for the following event: {{event}}

相关标签:
5条回答
  • 2020-12-11 23:33

    Use preg_replace_callback:

    $data = array(
        'name' => 'John Doe',
        'event' => 'Party yay!',
        'author' => 'Kehke Lunga',
    );
    
    $str = 'Dear {{name}},
    You are being invited for the following event: {{event}}
    regards, {{author}}';
    
    $str = preg_replace_callback('/{{(\w+)}}/', function($match) use($data) {
        return $data[$match[1]];
    }, $str );
    
    echo($str);
    

    output:

    Dear John Doe,
        You are being invited for the following event: Party yay!
        regards, Kehke Lunga
    
    0 讨论(0)
  • 2020-12-11 23:36

    With preg_match_all():

    $pattern = '~\{\{(.*?)\}\}~';
    preg_match_all($pattern, $string, $matches);
    var_dump($matches[1]);
    
    0 讨论(0)
  • 2020-12-11 23:37
    $matches = array();
    $a="{{name}}";
    preg_match('/\{(.+)\{(.+)\}\}/', $a, $matches);
    
    var_dump($matches);
    
    0 讨论(0)
  • 2020-12-11 23:38

    And for the second operations you need it could be something this way:

    $str = "Dear {{name||email}}, You are being invited for the following event: {{event}}. Regards, {{author}}";
    
    // $data['name'] = 'John Doe'; 
    $data['email'] = 'JohnDoe@unknown.com'; 
    $data['event'] = 'Party yay!'; 
    $data['author'] = 'Kehke Lunga';
    
    $pattern = '/{{(.*?)[\|\|.*?]?}}/';
    
    $replace = preg_replace_callback($pattern, function($match) use ($data)
    {
        $match = explode('||',$match[1]);
    
        return isset($data[$match[0]]) ? $data[$match[0]] : $data[$match[1]] ;
    }, $str);
    
    echo $replace;
    

    Basically by editing the '$pattern', and then find the correct logic needed inside the callback.

    0 讨论(0)
  • 2020-12-11 23:38

    Use preg_match to match the text between 2 curly braces :

    $subject = "{{Lorem}}";
    $pattern = '/\{\{([^}]+)\}\}/';
    preg_match($pattern, $subject, $matches);
    var_dump($matches);
    

    Take a look at similar Question

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