duanchao4445 2012-03-21 09:58
浏览 268
已采纳

正则表达式:匹配所有直到某个单词(PHP)

I'm processing a file with PHP.

This file contains a few blocks, which always start with the word "Step" (step 1, step 2 etc), and always end with "end step". Withing, it can have newlines, but never 2 consequently.

I'm trying to build a regex that will turn this into an array.

What I have so far is

preg_match_all("/Step([^\"end step\"]*)/s", $content, $matches);

The /s at the end of the patnern is to allow newslines to be included too. But of course, this does not work since all letters from "end step" are excluded, not only if they form 1 word. How can I write the correct regex?

  • 写回答

1条回答 默认 最新

  • dongshiran7000 2012-03-21 10:02
    关注

    One simple way:

    preg_match_all('/Step(.*?)"end step"/s', $content, $matches);
    

    This matches any text from Step to the nearest "end step". But it needs to backtrack after every single character which could be slow.

    Slightly more explicit and possibly more efficient::

    preg_match_all('/Step((?:(?!"end step").)*)/s', $content, $matches);
    

    This matches all the text from Step up to but not including the nearest "end step". It will match until the end of the string if "end step" never comes. This regex looks ahead at every step to check whether the string "end step" could be matched there and ends the match if that's true.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)