【问题标题】:regex wrap li with ul正则表达式用 ul 包裹 li
【发布时间】:2014-11-21 04:39:47
【问题描述】:

我需要用 ul 标签包装多组 li 标签。这是一个示例:

<text>
<p>Today is a nice day</p>
<li>This is line one</li>
<li>This is line two</li>
<li>This is line three</li>
</text>
<text>
<p>Today is also a nice day</p>
<li>This is also line one</li>
<li>This is also line two</li>
<li>This is also line three</li>
</text>

这是我正在使用的正则表达式:

/(&lt;li&gt;.*?&lt;\/li&gt;)+/g

当我尝试将所选字符串替换为:

&lt;ul&gt;$1&lt;/ul&gt; 

我得到以下信息:

<text>
<p>Today is a nice day</p>
<ul><li>This is line one</li></ul>
<ul><li>This is line two</li></ul>
<ul><li>This is line three</li></ul>
</text>
<text>
<p>Today is also a nice day</p>
<ul><li>This is also line one</li></ul>
<ul><li>This is also line two</li></ul>
<ul><li>This is also line three</li></ul>
</text>

这是我想要的结果:

<text>
<p>Today is a nice day</p>
<ul><li>This is line one</li></ul>
<ul><li>This is line two</li></ul>
<ul><li>This is line three</li></ul>
</text>
<text>
<p>Today is also a nice day</p>
<ul>
<li>This is also line one</li>
<li>This is also line two</li>
<li>This is also line three</li>
</ul>
</text>

【问题讨论】:

  • 为什么要得到上面这样的结果?
  • 使用domdocument 代替正则表达式

标签: php regex


【解决方案1】:

您必须在一个匹配项中匹配所有 &lt;il&gt; 标签,因此您需要使用某种多行模式:s 修饰符使 . 匹配换行符:

/(</p><li>.*?</li></text>)+/is

同时检查this question/answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    相关资源
    最近更新 更多