Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

php - Regex extract string between 2 curly braces

I have the following short codes:

Dear {{name}},

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

regards, {{author}}

I have an array from the database : $data

where:

$data['name'] = 'John Doe';
$data['event'] = 'Party yay!';
$data['author'] = 'Kehke Lunga';

Output that I expect:

Dear John Doe,

You are being invited for the following event: Party yay!

regards, Kehke Lunga

also, I also want to perform operations like {{firstname||lastname}} which should either check if key $data['firstname'] is set, if it isn't it should use $data['lastname']. However, that is for later stage.

For now, I just want to know how to match the text between 2 curly braces.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With preg_match_all():

$pattern = '~{{(.*?)}}~';
preg_match_all($pattern, $string, $matches);
var_dump($matches[1]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...