P/S:我是PHP程序员。给定:
div{3|5|6|9}[id = abc| class=image], a[id=link|class=out]我想使用正则表达式生成一个数组形式的结果,例如:
数组(
[div] => array(
"3|5|6|9",
"id = abc| class=image"
)
[a] => array(
"",
"id=link|class=out"))
有谁能帮帮忙吗?非常感谢!
发布于 2010-10-30 02:48:29
试试这个:
$str='div{3|5|6|9}[id = abc| class=image], a[id=link|class=out]';
preg_match_all('/(\w+)(\{(.*?)\})?\[(.*?)\](?:, |$)?/', $str, $m);
$out = array($m[1][0] => array($m[3][0], $m[4][0]), $m[1][1] => array($m[3][1], $m[4][1]));
print_r($out);输出:
Array
(
[div] => Array
(
[0] => 3|5|6|9
[1] => id = abc| class=image
)
[a] => Array
(
[0] =>
[1] => id=link|class=out
)
)发布于 2010-10-30 00:16:10
如果您可以保证{和}之间以及[和]之间不存在逗号,则可以首先按,拆分字符串,然后使用以下正则表达式:
/([a-z]+)(\{(.*?)\})?\[(.*?)\]/您想要捕获的组是$1、$3和$4 (如果使用preg_match_all,这些反向引用编号应该匹配)
注意:我在Javascript中测试过这个。
发布于 2010-10-30 22:28:21
preg_match_all('/(\w+)(\{(.*?)\})?\[(.*?)\](?:, |$)?/', $str, $m);我相信上面的代码可以很好地工作,除非另一个字符串像这样:
$str='div{3|5|6|9}[id = abc| class=image], a[id=link|class=out], br, ul';正则表达式不会捕获br和ul。
https://stackoverflow.com/questions/4053714
复制相似问题