【发布时间】: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