【问题标题】:Catching different syntax with Regular Expression使用正则表达式捕获不同的语法
【发布时间】:2013-05-25 06:18:23
【问题描述】:

我将在 HTML 中嵌入代码,它看起来像这样:

<div id="someDiv">
{:
    HTMLObject
    id: form
    background: blue
    font: large
    fields [
        username: usr
        password: pwd
    ]

    foo: bar
:}
</div>

我正在尝试编写一个正则表达式,它将获取这些 HTMLObject 并将它们分解为可管理的数组。我已经有了正则表达式,可以执行诸如

之类的行
id: form

但是,我无法让正则表达式也匹配类似

fields [
    username: usr
    password: pwd
]

这是执行这些任务的函数:

function parseHTMLObjects($html) {
    $details = preg_replace('/[{:]([^}]+):}/i', '$1', $html);
    $details = trim(str_replace('HTMLObject', '', $details));

    $dynamPattern = '/([^\[]+)\[([^\]]+)]/';
    $dynamMatch = preg_match_all($dynamPattern, $details, $dynamMatches);

    print_r($dynamMatches); // nothing is shown here

    $findMatch = preg_match_all('/([^:]+):([^\n]+)/', $details, $matches);

    $obs = array();
    foreach($matches[0] as $o) {
        $tmp = trim($o);
        echo $tmp . "\n";
    }
}

当我像在页面开头演示的那样传递一个 HTML 字符串时,$findMatch 正则表达式工作正常,但没有任何内容存储在 dynams 中。我是不是走错了路?

基本上我所需要的只是将每个对象存储在一个数组中,因此从上面的示例 HTML 字符串来看,这将是一个理想的数组:

Array() {
    [0] => id: form
    [1] => background: blue
    [2] => font: large
    [3] => fields [
               username: usr
               password: pwd
           ]
    [4] => foo: bar
}

我已经处理了超出该点的所有排序和操作,但就像我说的那样,我无法获得处理冒号样式对象的相同正则表达式来处理括号样式对象。

如果我需要使用不同的正则表达式并将结果存储在不同的数组中也可以。

【问题讨论】:

  • 为什么不使用 YAML 或 JSON?

标签: php regex preg-match preg-match-all pcre


【解决方案1】:

使用一些名为 YAML 或 JSON 的黑色魔法很容易使用这些语法:

YAML

{:
    HTMLObject:
      id: form
      background: blue
      font: large
      fields: [
        username: usr,
        password: pwd
      ]
      foo: bar
:}

JSON

{:
    { 
      "HTMLObject":{
        "id": "form",
        "background": "blue",
        "font": "large",
        "fields": [
          {"usernamd": "usr"},
          {"password": "pwd"}
        ],
        "foo": "bar"
      }
    }
:}

不-不-但是为什么?因为它是本地解析的。没有脏的正则表达式。

【讨论】:

  • 谢谢,我用过一点JSON,这次我想试试YAML。
【解决方案2】:

我还不能对帖子发表评论,但绝对是寻找从一种符号到 php 数组的转换函数是前进的方向,json_decode 就是其中之一,尽管您的数据正在以其他方式开始生命。

正则表达式对于复杂的数据可能非常棘手,因为它具有一些其他结构,可以更好地使用其他工具进行解释

PS 如果你确实在任何时候在 php 中使用 json_decode,不要被第二个参数抓住 - 它需要设置为 'true' 才能获得一个数组!

【讨论】:

    猜你喜欢
    • 2012-01-02
    • 2022-11-21
    • 1970-01-01
    • 2020-01-20
    • 2011-03-05
    • 1970-01-01
    • 2021-08-19
    • 2021-12-10
    • 2014-01-02
    相关资源
    最近更新 更多