【问题标题】:regular expression new line between tags标签之间的正则表达式换行
【发布时间】: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。其次 - 你从来没有编写过正则表达式,对吗?
  • 看起来你对正则表达式语法很困惑。 [\&lt;ul\&gt;\&lt;li\&gt;] 等价于[&lt;&gt;ilu],它匹配括号之间的任何字符。如果您尝试匹配&lt;ul&gt;&lt;li&gt; 中的任何一个,则应使用&lt;(ul|li)&gt;。与[h1] 类似,匹配h1
  • 它删除了&lt;/ul&gt;&lt;/li&gt; 标签,因为它们在新行上,我该如何防止这种情况发生。
  • Jaap:那个正则表达式完全不合时宜。你可以从一张干净的床单开始,防止你观察到的任何错误。单独使用诸如字符类、子模式和量词之类的单个构造,以感受它们的效果。只有这样才能回到你现在的任务。说真的,扔掉这个无意义的正则表达式。

标签: php regex


【解决方案1】:

我不完全确定您要达到的目标,但我认为纠正模式应该是这样的:

#\s*(<ul><li>)?(\s*<(p|h1|h2|h3)>)*(.+?)(</(p|h1|h2|h3)>\s*)*(</li></ul>)?#is

编辑:更正一个错误

【讨论】:

  • "#()*(.*?)(.+?)(p|h1|h2| h3)>(.*?)((ul|li)>)*#is" 这对我有用,现在让我试试你的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
相关资源
最近更新 更多