php中的正则表达式:取最短匹配 [英] regular expression in php: take the shortest match
问题描述
我正在尝试做一个 PHP 正则表达式,但我找不到正确的方法......
I'm trying to do a PHP regular expression but i can't find the right way ...
想象一下我有这个字符串:你好,我的{{name is Peter}}和{{我想吃巧克力}}"
Imagine I have this string: "hello, my {{name is Peter}} and {{I want to eat chocolate}}"
我想取{{和}}之间的部分
I want to take the parts between {{ and }}
但是如果我使用 preg_match("/\{\{(.*)?\}\}/", $string)
它只返回一个字符串{{name is Peter}} 和{{我想吃巧克力}}"
it returns me jut one string "{{name is Peter}} and {{I want to eat chocolate}}"
我怎样才能判断出}} 的第一个巧合?
How can I tell to take the first coincidences of }} ?
谢谢
推荐答案
使用
"/{{(.*?)}}/"
表达式 ".*"
是贪婪的,取尽可能多的字符.如果您使用 ".*?"
则需要尽可能少的字符,即它停在第一组右括号处.
The expression ".*"
is greedy, taking as many characters as possible.
If you use ".*?"
is takes as little characters as possible, that is it stops at the first set of closing brackets.
这篇关于php中的正则表达式:取最短匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!