Php preg_替换混乱

Php preg_替换混乱,php,regex,preg-replace,Php,Regex,Preg Replace,在包含一些html的字符串中,我想查找并替换标记的每次出现,包括它后面的任何内容,直到另一个标记或html字符串结束 我的模式:您有几个问题: 您需要g(全局)标志来获取多个匹配项 您需要添加$(字符串结尾)作为前瞻的替代选项,以便它可以匹配最后一个标记的字符串结尾 这应该满足您的要求: <h\d.+?(?=<h\d|$) asiponfpweg ihnasegioad 随便 [1] =>attribute=“无论什么”>asiponfpweg ihnasego 随便 随便 [2]

在包含一些html的字符串中,我想查找并替换
标记的每次出现,包括它后面的任何内容,直到另一个
标记或html字符串结束


我的模式:
您有几个问题:

  • 您需要
    g
    (全局)标志来获取多个匹配项
  • 您需要添加
    $
    (字符串结尾)作为前瞻的替代选项,以便它可以匹配最后一个
    标记的字符串结尾
  • 这应该满足您的要求:

    <h\d.+?(?=<h\d|$)
    
    asiponfpweg ihnasegioad
    随便

    [1] =>attribute=“无论什么”>asiponfpweg ihnasego 随便

    随便

    [2] =>attribute=“无论什么”>asiponfpweg ihnasego 随便

    [3] =>attribute=“无论什么”>asiponfpweg ihnasego )

    在本例中,您的目标不仅仅是H2。如果我真的理解,您希望找到所有使用此格式的事件*对我来说,它应该可以工作。请给我们看一下示例输入。结果表明,示例输入在某种程度上是不同的。我更新了我的文章的细节。我应该提到,我正试图使这与preg_取代工作。我已经重写了我的问题。@bewww很抱歉没有回应-这里已经是晚上了。我想您已经解决了这个问题,但是相同的正则表达式在
    preg\u replace
    中运行良好,请参见
    <h\d.+?(?=<h\d|$)
    
    preg_match_all('/<h\d.+?(?=<h\d|$)/s', $html, $matches);
    print_r($matches[0]);
    
    Array
    (
        [0] => <h1> attribute="whatever">asiponfpweg ihnasegio</h1>asd
    <p>whatever</p>
    <img src=""></img>
        [1] => <h3> attribute="whatever">asiponfpweg ihnasegio</h3>
    <p>whatever</p>
    <p>whatever</p>
        [2] => <h1><span> attribute="whatever">asiponfpweg ihnasegio</span></h3>
    <p>whatever</p>
        [3] => <h3> attribute="whatever">asiponfpweg ihnasegio</h3>
    )