正则表达式包裹着ul

时间:2014-11-21 04:39:48

标签: php regex

我需要用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>

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

/(<li>.*?<\/li>)+/g

当我尝试用:

替换所选字符串时

<ul>$1</ul> 

我得到以下内容:

<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>

1 个答案:

答案 0 :(得分:0)

您必须在一次匹配中匹配所有<il>代码,因此您需要使用某种风格的多线模式:s修饰符使.与换行匹配:

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

同时检查this question/answer