我在HTML中有一些HTML有序/无序列表。由于要将其导出到txt文件,因此需要将其转换为纯文本。
例如原始HTML:
<ol><li>Item 1</li></li>Item 2</li><li>Item 3</li></ol>
我想将其更改为
1. Item 1
2. Item 2
3. Item 3
我在StackOverflow上进行搜索,但只找到了相反转换的解决方案。 A regex that converts text lists to html in PHP
有什么办法可以处理?谢谢!
您可以简单地替换不需要的标签,并在一个标签上爆炸它,该标签将为每一行返回自身。
<?php
$html = '
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
';
$html = str_replace(['<ol>', '</ol>', '</li>'], '', $html);
$html = explode('<li>', $html);
print_r($html);
我认为这不仅比正则表达式还要复杂,特别是如果您想在前面加上数字。但是,这小段代码会将<ol><li>Item 1</li></li>Item 2</li><li>Item 3</li></ol>
转换为
* Item 1
* Item 2
* Item 3
<?php
$string = "<ol><li>Item 1</li><li>Item 2</li><li>Item 3</li></ol>";
$string= preg_replace("/<li>/", " * ", $string);
$string= preg_replace("/<\/li>/", "\n", $string);
$string= preg_replace("/<\/?ol>/", "", $string);
echo $string;
请查看html2text库。它有多种方法可以将HTML
字符串转换为纯文本。