【发布时间】:2012-07-04 12:04:04
【问题描述】:
我有一个带有正则表达式的 php 代码,它在 li 标记内 p 标记的新行上失败。当我执行此代码时,它会从中删除 </ul></li>。
<?php
$data = "<h1>test</h1>
<h2>test</h2>
<p>This is not real text but just a test, This is not real text but just a test, This is not real text but just a test, This is not real text but just a test, This is not real text but just a test</p>
<ul><li><p>This is not real text but just a test, This is not real text but just a test, This is not real text but just a test, This is not real text but just a test</p>
</li></ul>
<ul><li><p>This is not real text but just a test, This is not real text but just a test, This is not real text but just a test, This is not real text but just a test</p>
</li></ul>";
$pattern = "#[\<ul\>\<li\>]*\<[p]*[h1]*[h2]*[h3]*\>(.+?)\</[p]*[h1]*[h2]*[h3]*\>[\</li\>\</ul\>]*#is";
preg_match_all($pattern, $data, $output);
var_dump($output);
?>
谁能帮我解决这个问题?
【问题讨论】:
-
只是一个问题 - 你到底想做什么?
-
首先 - NOT 使用正则表达式解析 HTML。其次 - 你从来没有编写过正则表达式,对吗?
-
看起来你对正则表达式语法很困惑。
[\<ul\>\<li\>]等价于[<>ilu],它匹配括号之间的任何字符。如果您尝试匹配<ul>或<li>中的任何一个,则应使用<(ul|li)>。与[h1]类似,匹配h或1。 -
它删除了
</ul></li>标签,因为它们在新行上,我该如何防止这种情况发生。 -
Jaap:那个正则表达式完全不合时宜。你可以从一张干净的床单开始,防止你观察到的任何错误。单独使用诸如字符类、子模式和量词之类的单个构造,以感受它们的效果。只有这样才能回到你现在的任务。说真的,扔掉这个无意义的正则表达式。