PHP中正则表达式匹配顺序的问题

时间:2010-12-09 14:58:56

标签: php regex

我有以下示例文本

The quick brown {fox} jumps over the lazy {dog}

我需要匹配{}中包含的任何字符串,这些字符串可能会在文本中多次出现 我尝试了以下代码,但它无法正常工作

<?php

$matches = array();

$string = "The quick brown {fox} jumps over the lazy {dog}";

preg_match("/\{(.*)\}/",$string,$matches);

print_r($matches);

?>

这就是我得到的

Array
(
    [0] => {fox} jumps over the lazy {dog}
    [1] => fox} jumps over the lazy {dog
)

我希望得到

Array
(
    [0] => {fox} jumps over the lazy {dog}
    [1] => fox
    [2] => dog
)

那么如何强制PHP匹配最近的“}”而不是匹配最后一个?

3 个答案:

答案 0 :(得分:3)

您现有的正则表达式.* 贪婪并尝试尽可能多地使用 。要解决此问题,您需要在结尾处添加?,以使正则表达式非贪婪

.*?

或者您也可以使用[^}]*代替.*

由于你想要所有的比赛,你需要使用preg_match_all

See it

答案 1 :(得分:0)

默认情况下,regexp以贪婪模式执行。你需要ungreedy。要么使用/ U开关,要么使用codaddict的建议*。?使表达的那部分不合理

答案 2 :(得分:0)

默认情况下,表达式是贪婪的,即他们试图抓住最长的匹配。你可以使用U标志表达不同的表达式:

preg_match('/\{(.*)\}/U', $string, $matches);