繁体   English   中英

如何使用正则表达式检测PHP中的列表或枚举

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM