2014-11-21 117 views
0

我需要用ul標籤包裝多組li標籤。下面是一個示例:正則表達式包裝與ul

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

爲什麼你想要得到如上的結果? – 2014-11-21 04:42:05

+0

使用[domdocument](http://php.net/manual/en/class.domdocument.php)而不是正則表達式 – gwillie 2014-11-21 04:43:43

+0

你的代碼在哪裏? – Manwal 2014-11-21 04:45:31

回答

0

你必須所有<il>標籤匹配在一個單一的比賽,所以你需要使用多行模式的一些風味:s修改器使.與換行符匹配:

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

另請檢查this question/answer