regular expression in php: take the shortest match

前端 未结 5 1546
我寻月下人不归
我寻月下人不归 2021-01-12 05:23

I\'m trying to do a PHP regular expression but i can\'t find the right way ...

Imagine I have this string: \"hello, my {{name is Peter}} and {{I want to eat chocolat

5条回答
  •  温柔的废话
    2021-01-12 05:58

    This worked for me.

    $subject = 'Hello {{name}}, here is an email {{email}} and phone # {{phone}}';
    $replace = array(
        '{{name}}' => 'Bob',
        '{{email}}' => 'email@me.com',
        '{{phone}}' => '5155554455'
    );
    
    $output = preg_replace_callback('{{{?(#[a-z]+ )?[a-z]+.[a-z]*}?}}', function($match) use ($replace) {
        if(isset($replace[$match[0]])){
            return ($replace[$match[0]]);
        } else {
            return($match[0]);
        } 
    }, $subject);
    
    var_dump($output);
    

提交回复
热议问题