[英]How can I use a regular expression to detect a list or enumeration in PHP
我從XML提要中獲取數據。 我無法控制供稿,也不可以滿足其內容。
有時,數據包含一個列表/枚舉。 我想將其解析為干凈的HTML無序列表。
我收到的數據將采用以下格式:
<p>Some text in a paragraph tag</p>
<p>
- List item one <br>
- List-item-two<br>
-List item three <br>
- Listitem four<br>
</p>
<p>Another paragraph with text, and maybe even more paragraphs after this one!
They might even contain - dashes - - - or <br><br> breaks!</p>
請注意,並非每個列表項都經過整齊的格式化。 有些包含在<br>
標記之間或破折號與文本之間的尾隨節奏。
我如何在PHP中對此進行后處理以獲得結果:
<p>Some text in a paragraph tag</p>
<p><ul>
<li>List item one</li>
<li>List-item-two</li>
<li>List item three</li>
<li>Listitem four</li>
</ul></p>
<p>Another paragraph with text, and maybe even more paragraphs after this one!
They might even contain - dashes - - - or <br><br> breaks!</p>
我可以使用正則表達式嗎? 如果是這樣,它將是什么樣?
是的,我認為正則表達式是一個很好的起點。 看看preg_replace
正則表達式可能是這樣的(未經測試):
$li = preg_replace('/^-([a-z]+)(<br>)?$/i', '<li>$1</li>', $entry);
當然這是行不通的(您需要對空格的支持等等),但是我想您已經明白了。
您可以通過將^-\\s*\\b(.+)\\b\\s*<br>$
替換為<li>$1</li>
。 我將把所有內容包裝在<ul/>
的困難部分留給您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.