代码之家  ›  专栏  ›  技术社区  ›  Jacek Kowalewski

PHP(正则表达式)未知单词,带有特殊字符。字符“配对匹配”

  •  -2
  • Jacek Kowalewski  · 技术社区  · 11 年前

    我不知道,如何使主题(标题)足够清楚,以便理解。 我有这样的东西:

    <h2>Title</h2>
    <<navigation id="submenu">>
        <<main level="1" asd="2">>
        <<main level="1" asd="2">>
        <<notmain>>asd<</notmain>>
    <</navigation>>
    <p><a href="..">asd</a>asdasdasd</p>
    Oh no! The great rabbit is attacking us, and we are 
    only knights of a square table!
    <h2>Here another tag can occur</h2>
    <<footer>>
        <<copyright id="copy">>
    <</footer>>
    

    我必须找到并记住(作为文本)具有两个标记的对象,而不是一个标记(但只有主父标记)。因此,对于这个示例,我需要输出如下内容:

    array(
        0 => '<<navigation id="submenu">><<main level="1" asd="2">><<main level="1" asd="2">><<notmain>>asd<</notmain>><</navigation>>',
        1 => '<<footer>><<copyright id="copy">><</footer>>';
    

    空格、空白、制表符和其他都不重要,因为使用trim和str_replace很容易去除它们。唯一的问题是搜索方法。

    我试图正则化这个,但没有什么问题。

    1. 我只对父母感兴趣。所以在内部没有递归搜索,只在元素外部使用“<<''>>'以及所有内部元素(不在乎它们看起来如何)。
    2. 我没有第一个单词的任何数据。它可以是<>。然后返回全部:)。我不知道,如果正则表达式能够记住它找到的内容,我也没有找到任何解决方案。

    我希望我的问题是清楚的。

    我非常了解PHP,所以没有代码或想法的文本解决方案也会很有用。

    如果有一个没有正则表达式的解决方案,那就太好了。当然有一个残酷的解决方案,(一个字符接着一个字符分析)但它需要大量的代码。。。

    1 回复  |  直到 6 年前
        1
  •  1
  •   edmondscommerce    11 年前

    这个怎么样:

    %^<<([^<]+?)>>$(.+?)^<<([^<]+?)>>%sm

    与一起使用时会产生此结果 preg_match_all

    array (
      0 => 
      array (
        0 => '<<navigation id="submenu">>
        <<main level="1" asd="2">>
        <<main level="1" asd="2">>
        <<notmain>>asd<</notmain>>
    <</navigation>>',
        1 => '<<footer>>
        <<copyright id="copy">>
    <</footer>>',
      ),
      1 => 
      array (
        0 => 'navigation id="submenu"',
        1 => 'footer',
      ),
      2 => 
      array (
        0 => '
        <<main level="1" asd="2">>
        <<main level="1" asd="2">>
        <<notmain>>asd<</notmain>>
    ',
        1 => '
        <<copyright id="copy">>
    ',
      ),
      3 => 
      array (
        0 => '/navigation',
        1 => '/footer',
      ),
    )