【发布时间】:2021-10-09 02:33:34
【问题描述】:
我有一些字符串格式的内容,包括一些不需要的 html 标记及其内容。我正在寻找一种删除它们的方法,但仍然找不到完美的解决方案。
方法一
通常,我们使用strip_tags 来删除标签,但它会保留标签内的文本内容。
方法二
然后我尝试使用preg_replace 来删除标签以及使用/<font[\s\S].*?<\/font>/ 等模式的内容
测试
但在实际情况中,标签有时会包含相同的标签,例如
text to keep <span xxx="xxxx"><span xxx="xxx">unwanted text</span> unwanted text </span> text to keep ...<some other tags>
使用这两种方法都不会得到想要的结果。
方法一输出
unwanted text unwanted text text to keep
方法二输出
unwanted text </span> text to keep
存档的最佳方式是什么?
我正在寻找这样的解决方案(我知道这种模式不起作用):
$remove_arr = [
'span',
'div',
'strong'
]
foreach($remove_arr as $remove){
$content = preg_replace("/<$remove.*?<\/$remove>/", '',$content);
}
先谢谢各位了!
更新
代码位于名为 Collect.php 的文件中
<?php
namespace app\common\model;
use think\Db;
use think\Cache;
use app\common\util\Pinyin;
use think\Request;
class Collect extends Base {
//the code
}
【问题讨论】: