edit inquiry
This commit is contained in:
@@ -220,4 +220,52 @@ if (!function_exists('removeParentheses')) {
|
||||
|
||||
return trim(preg_replace($pattern, '', $str, 1));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范hmtl富文本
|
||||
*/
|
||||
if (!function_exists('normalizeRichText')) {
|
||||
function normalizeRichText(string $html): string
|
||||
{
|
||||
$dom = new DOMDocument();
|
||||
|
||||
// 处理UTF-8编码和HTML5标签
|
||||
@$dom->loadHTML('<?xml encoding="UTF-8">' . $html,
|
||||
LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
|
||||
|
||||
// 设置编码并规范化文档
|
||||
$dom->encoding = 'UTF-8';
|
||||
$dom->normalizeDocument();
|
||||
|
||||
// 统一处理空白字符
|
||||
$xpath = new DOMXPath($dom);
|
||||
foreach ($xpath->query('//text()') as $node) {
|
||||
$normalized = preg_replace('/\s+/u', ' ', trim($node->nodeValue));
|
||||
$node->nodeValue = $normalized;
|
||||
}
|
||||
|
||||
// 标准化属性顺序(可选)
|
||||
foreach ($xpath->query('//*[@*]') as $element) {
|
||||
$attributes = $element->attributes;
|
||||
$sorted = [];
|
||||
foreach ($attributes as $attr) {
|
||||
$sorted[$attr->nodeName] = $attr->nodeValue;
|
||||
}
|
||||
ksort($sorted);
|
||||
|
||||
// 移除所有属性后按排序后顺序重新添加
|
||||
while ($attributes->length) {
|
||||
$element->removeAttributeNode($attributes->item(0));
|
||||
}
|
||||
foreach ($sorted as $name => $value) {
|
||||
$element->setAttribute($name, $value);
|
||||
}
|
||||
}
|
||||
|
||||
// 返回规范化后的HTML
|
||||
$result = trim($dom->saveHTML());
|
||||
// 替换所有空白实体为普通空格
|
||||
return preg_replace('/\s+/u', ' ', $result);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user