【问题标题】:PHP - Preg_match shortest matchesPHP - Preg_match 最短匹配
【发布时间】:2015-10-26 07:25:11
【问题描述】:

我正在尝试从此字符串中获取“内容”:

$string = "start start content end";

像这样使用 preg_match:

preg_match('/start(.*?)end/', $string, $matches);
echo $match[1];

但是,问题是$matches[1] 返回start content 不仅是content,因为$string 中有两个start(可能还有更多)

如何仅获得content 部分和preg_match

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    使用负前瞻:

    $string = "start start content end";
    preg_match('/start\h*((?:(?!start).)*)end/', $string, $matches);
    echo $matches[1];
    // content
    

    (?:(?!start).) 将匹配任何后面没有start 的字符。

    【讨论】:

    • (?:(?!start).)* 是所谓的tempered greedy token
    • 你的答案对我有用。谢谢你和@arunesh-singh
    • \h*有什么用?在这里看起来是多余的。
    • 没有\h* 输出将是" content" 而不是"content"
    【解决方案2】:

    您可以添加+ 吃掉所有start,然后捕获您需要的字符串。

    (?:start\s)+(.+?)end
    

    【讨论】:

    • 有趣,因为 OP 使用的是preg_match,所以这种方法可能是有效的,但使用像(?:.*start\s)+(.+?)end 这样的正则表达式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多