php - 使用正则表达式和 DOMDocument 递归处理标记

标签 php regex domdocument

我一直在努力为我正在开发的 HTML 标记语言的基本文本创建解析器。内联元素标记如下。

{*strong*}
{/emphasis/}
{-strikethrough-}
{>small<}
{|code|}

我正在测试的示例字符串是:

tëstïng 汉字/漢字 testing {*strông{/ëmphäsïs{-strïkë{|côdë|}-}/}*} {*wôw*} 1, 2, 3

使用 preg_split 我可以将其转换为:

$split = preg_split('%(\{.(?:[^{}]+|(?R))+.\})%',
    $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

array (size=5)
  0 => string 'tëstïng 汉字/漢字 testing ' (length=32)
  1 => string '{*strông{/ëmphäsïs{-strïkë{|côdë|}-}/}*}' (length=48)
  2 => string ' ' (length=1)
  3 => string '{*wôw*}' (length=8)
  4 => string ' 1, 2, 3' (length=8)

然后循环遍历 $dom->createTextNode()$dom->createElement() + $dom->appendChild($dom->创建文本节点())。不幸的是,这在嵌套标记时没有帮助。

我只是对一种将我的标记递归处理为 DOMDocument 的有效方法感到困惑。我一直在阅读,我需要编写一个解析器,但找不到我可以遵循的合适的教程或代码示例,尤其是在使用 DOMDocument 将其与元素和文本节点创建集成时。

最佳答案

嵌套或递归结构通常超出了正则表达式的解析能力,您通常需要更强大的解析器。问题是您需要查找的下一个标记会根据先前的标记发生变化,这不是正则表达式可以处理的(语言不再是正​​则的)。

然而,对于这样一种简单的语言,您不需要具有正式语法的完整的解析器生成器——您可以轻松地手动编写一个简单的解析器。您只有一个重要的状态——最后打开的标签。如果您有匹配文本的正则表达式、新的打开标签或与当前打开标签对应的关闭标签,则可以处理此任务。规则是:

  1. 如果匹配文本,保存文本并继续匹配。
  2. 如果匹配到一个开放标签,保存开放标签,并继续匹配,直到找到一个开放标签或相应的结束标签。
  3. 如果匹配关闭标签,则停止查找当前打开的标签并继续匹配上次未关闭的标签、文本或其他打开标签。

第二步是递归的——每当你找到一个新的开始标签时,你就创建一个新的匹配上下文来寻找相应的结束标签。

这不是必需的,但通常解析器会生成一个简单的树结构来表示已解析的文本——这被称为抽象语法树。通常最好先生成语法树,然后再生成语法表示的内容。这使您可以灵活地操作树或生成不同的输出(例如,您可以输出 xml 以外的内容。)

这是一个结合了这两种想法并解析您的文本的解决方案。 (它还将 {{}} 识别为转义序列,表示单个文字 {}。)

首先是解析器:

class ParseError extends RuntimeException {}

function str_to_ast($s, $offset=0, $ast=array(), $opentag=null) {
    if ($opentag) {
        $qot = preg_quote($opentag, '%');
        $re_text_suppl = '[^{'.$qot.']|{{|'.$qot.'[^}]';
        $re_closetag = '|(?<closetag>'.$qot.'\})';
    } else {
        $re_text_suppl = '[^{]|{{';
        $re_closetag = '';
    }
    $re_next = '%
        (?:\{(?P<opentag>[^{\s]))  # match an open tag
              #which is "{" followed by anything other than whitespace or another "{"
        '.$re_closetag.'  # if we have an open tag, match the corresponding close tag, e.g. "-}"
        |(?P<text>(?:'.$re_text_suppl.')+) # match text
            # we allow non-matching close tags to act as text (no escape required)
            # you can change this to produce a parseError instead
        %ux';
    while ($offset < strlen($s)) {
        if (preg_match($re_next, $s, $m, PREG_OFFSET_CAPTURE, $offset)) {
            list($totalmatch, $offset) = $m[0];
            $offset += strlen($totalmatch);
            unset($totalmatch);
            if (isset($m['opentag']) && $m['opentag'][1] !== -1) {
                list($newopen, $_) = $m['opentag'];
                list($subast, $offset) = str_to_ast($s, $offset, array(), $newopen);
                $ast[] = array($newopen, $subast);
            } else if (isset($m['text']) && $m['text'][1] !== -1) {
                list($text, $_) = $m['text'];
                $ast[] = array(null, $text);
            } else if ($opentag && isset($m['closetag']) && $m['closetag'][1] !== -1) {
                return array($ast, $offset);
            } else {
                throw new ParseError("Bug in parser!");
            }
        } else {
            throw new ParseError("Could not parse past offset: $offset");
        }
    }
    return array($ast, $offset);
}

function parse($s) {
    list($ast, $offset) = str_to_ast($s);
    return $ast;
}

这将产生一个抽象语法树,它是一个“节点”列表,其中每个节点都是一个数组,格式为 array(null, $string) for text 或 array( '-', array(...))(即类型代码和另一个节点列表)用于标记内的内容。

一旦你有了这棵树,你就可以用它做任何你想做的事。例如,我们可以递归地遍历它来生成一个 DOM 树:

function ast_to_dom($ast, DOMNode $n = null) {
    if ($n === null) {
        $dd = new DOMDocument('1.0', 'utf-8');
        $dd->xmlStandalone = true;
        $n = $dd->createDocumentFragment();
    } else {
        $dd = $n->ownerDocument;
    }
    // Map of type codes to element names
    $typemap = array(
        '*' => 'strong',
        '/' => 'em',
        '-' => 's',
        '>' => 'small',
        '|' => 'code',
    );

    foreach ($ast as $astnode) {
        list($type, $data) = $astnode;
        if ($type===null) {
            $n->appendChild($dd->createTextNode($data));
        } else {
            $n->appendChild(ast_to_dom($data, $dd->createElement($typemap[$type])));
        }
    }
    return $n;
}

function ast_to_doc($ast) {
    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->xmlStandalone = true;
    $root = $doc->createElement('body');
    $doc->appendChild($root);
    ast_to_dom($ast, $root);
    return $doc;
}

下面是一些带有更难测试用例的测试代码:

$sample = "tëstïng 汉字/漢字 {{ testing -} {*strông 
    {/ëmphäsïs {-strïkë *}also strike-}/} also {|côdë|}
    strong *} {*wôw*} 1, 2, 3";
$ast = parse($sample);
echo ast_to_doc($ast)->saveXML();

这将打印以下内容:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<body>tëstïng 汉字/漢字 {{ testing -} <strong>strông 
    <em>ëmphäsïs <s>strïkë *}also strike</s></em> also <code>côdë</code>
    strong </strong> <strong>wôw</strong> 1, 2, 3</body>

如果您已经有一个 DOMDocument 并且想向其中添加一些已解析的文本,我建议您创建一个 DOMDocumentFragment 并将其传递给 ast_to_dom 直接,然后将其附加到您想要的容器元素。

关于php - 使用正则表达式和 DOMDocument 递归处理标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15857560/

相关文章:

regex - 仅过滤文件中的大写单词

php - 无法打印_r domDocument

angular - 打开第二个时关闭下拉菜单/document.click被点击Angular 5阻止

java - openssl_encrypt 不带 vector 的 AES 加密

php - 从不同表中收集条目的 SQL 查询 - 需要 UNION 的替代方法

regex - 有没有更好的方法用/x 编写 Perl 正则表达式,这样代码仍然易于阅读?

PHP DOM UTF-8 问题

php - ucwords 在斜杠 (/) 符号后不起作用

php - 类似于 Python 中 PHP 的 SimpleXML 的东西?

java - 正则表达式 CSV 格式的钱