我将在HTML中嵌入代码,它看起来像这样:
<div id="someDiv">
{:
HTMLObject
id: form
background: blue
font: large
fields [
username: usr
password: pwd
]
foo: bar
:}
</div>
我正试图写一个正则表达式,将这些html对象,并将它们分解成可管理的数组。我已经有了regexp,它将处理像
这样的行id: form
然而,我有麻烦,使regexp也匹配像
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
regexp工作得很好,但是dynams regexp中没有存储任何东西。我是不是走错路了?
Array() {
[0] => id: form
[1] => background: blue
[2] => font: large
[3] => fields [
username: usr
password: pwd
]
[4] => foo: bar
}
我已经处理了所有的排序和操作,但是就像我说的,我在处理冒号风格对象的regexp也处理括号风格对象时遇到了麻烦。
如果我需要使用不同的regexp并将结果存储在不同的数组中,这也很好。
这很容易用一些叫做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"
}
}
:}
Bu-bu-but为什么?因为它是原生解析的。没有脏的regexp
我还不能评论帖子,但肯定寻找从一种符号到php数组的转换函数是前进的方向,json_decode是一种,尽管您的数据开始作为其他东西。
regex对于复杂的数据可能非常棘手,因为它有一些其他的结构,可以用其他工具更好地解释
PS如果你在php中使用json_decode,不要被第二个参数捕获-它需要被设置为'true'来获得一个数组!