【问题标题】:Is it possible to replace div contents with regular expression?是否可以用正则表达式替换 div 内容?
【发布时间】:2011-06-17 22:31:38
【问题描述】:

是否可以编写一个正则表达式来替换<div id=”somevalue123” class=”text-block”></div> 之间的所有内容?我可以这样做,但我遇到的问题是字符串中还有其他 div 节点。

这是我正在使用的当前正则表达式:

public static function replaceStringBetween($start, $end, $new, $source, $limit = 1)
{
    // Reinitialize the replacement count
    self::$replacement_count = 0;

    // Try to perform the replacement
    $result = preg_replace('#('.preg_quote($start) . ')(.*)('.preg_quote($end) 
        . ')#is', '$1' . $new . '$3', $source, $limit, $count);
    if ($count > 0)
    {
        self::$replacement_count++;
        return $result;
    }

    // As a fallback, try again with a different method
    $result = preg_replace ("#{$start}(.*){$end}#is", $new, $source, $limit, $count);
    if ($count > 0)
    {
        self::$replacement_count++;
        return $result;
    }

    // Return the original
    return $source;
}

当然,我正在传递一个 HTML 文件作为源文件。 谢谢

【问题讨论】:

  • 最好使用适当的 XML 解析器。

标签: php regex replace


【解决方案1】:

Simple HTML DOM Parser 是一个简单易用的 PHP 解析器,我过去曾这样做过。您将使用选择器div#somevalue123

【讨论】:

    【解决方案2】:

    正则表达式不支持任意嵌套。您可能需要考虑使用下推自动机(解析器)进行任意嵌套。

    在实践中,您可以设计一系列正则表达式来解析固定数量的正则表达式。但是,一旦您开始处理错误条件和(解析)错误,您实际上是在尝试将正则表达式硬塞到解析器的位置。

    这似乎是您可能想要重新考虑您寻求的模块化方法和设计,而不是通过使用正则表达式诱饵和转换将其放入事后。

    【讨论】:

    • 现代“正则表达式”完全能够支持任意嵌套。我希望这些谎言不再被传播。
    • 你能给我举个例子吗?我并不是故意试图传播不实之词。我从四年前的正式语言和自动机课上记得这一点。
    • 谢谢。下次我需要在任意嵌套的东西上实现捕获时,我将尝试使用现代正则表达式。
    猜你喜欢
    • 2017-02-21
    • 1970-01-01
    • 2013-02-21
    • 2016-04-06
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多