|
|
@@ -714,4 +714,83 @@ if(! function_exists('str_cut_ellipsis'))
|
|
|
}
|
|
|
return mb_substr($str, 0, $len, 'UTF-8') . $dot;
|
|
|
}
|
|
|
+}
|
|
|
+
|
|
|
+if (! function_exists('filterHtmlTags'))
|
|
|
+{
|
|
|
+ /**
|
|
|
+ * 批量修改 HTML 中指定标签的属性和样式
|
|
|
+ *
|
|
|
+ * @param string $html 原始 HTML 内容
|
|
|
+ * @param array $rules 规则数组,键为标签名(小写),值为配置:
|
|
|
+ * [
|
|
|
+ * 'remove' => ['width', 'height'], // 要移除的属性名列表
|
|
|
+ * 'style' => ['width' => '100%', 'margin' => '0'] // 要强制设置/覆盖的样式
|
|
|
+ * ]
|
|
|
+ * @return string 处理后的 HTML
|
|
|
+ */
|
|
|
+ function filterHtmlTags($html, $rules) {
|
|
|
+ // 匹配所有标签的开始部分:<标签名 属性...> 或 <标签名 属性.../> 或 <标签名>
|
|
|
+ $pattern = '/<(\w+)(?:\s+([^>]*?))?\/?>/i';
|
|
|
+ return preg_replace_callback($pattern, function($matches) use ($rules) {
|
|
|
+ $tag = strtolower($matches[1]);
|
|
|
+ // 如果该标签不在规则中,直接返回原匹配
|
|
|
+ if (!isset($rules[$tag])) {
|
|
|
+ return $matches[0];
|
|
|
+ }
|
|
|
+ $rule = $rules[$tag];
|
|
|
+ // 解析属性(如果有)
|
|
|
+ $attrStr = isset($matches[2]) ? $matches[2] : '';
|
|
|
+ $attrArray = [];
|
|
|
+ if ($attrStr) {
|
|
|
+ // 匹配 属性名="值" 或 属性名='值' 或 属性名=值
|
|
|
+ preg_match_all('/([a-zA-Z-]+)\s*=\s*("([^"]*)"|\'([^\']*)\'|([^\s>]+))/', $attrStr, $matchesAttr, PREG_SET_ORDER);
|
|
|
+ foreach ($matchesAttr as $m) {
|
|
|
+ $name = strtolower($m[1]);
|
|
|
+ $value = isset($m[3]) ? $m[3] : (isset($m[4]) ? $m[4] : $m[5]);
|
|
|
+ $attrArray[$name] = $value;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 1. 移除指定属性
|
|
|
+ if (isset($rule['remove'])) {
|
|
|
+ foreach ($rule['remove'] as $attr) {
|
|
|
+ unset($attrArray[$attr]);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 2. 处理样式
|
|
|
+ if (isset($rule['style']) && is_array($rule['style'])) {
|
|
|
+ $oldStyle = isset($attrArray['style']) ? $attrArray['style'] : '';
|
|
|
+ $styles = [];
|
|
|
+ if ($oldStyle) {
|
|
|
+ // 简单解析,按分号分割
|
|
|
+ $parts = array_filter(array_map('trim', explode(';', $oldStyle)));
|
|
|
+ foreach ($parts as $part) {
|
|
|
+ if (strpos($part, ':') !== false) {
|
|
|
+ list($key, $value) = array_map('trim', explode(':', $part, 2));
|
|
|
+ $styles[$key] = $value;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // 强制覆盖(或添加)样式
|
|
|
+ foreach ($rule['style'] as $key => $value) {
|
|
|
+ $styles[$key] = $value;
|
|
|
+ }
|
|
|
+ // 重组 style
|
|
|
+ $newStyle = '';
|
|
|
+ foreach ($styles as $k => $v) {
|
|
|
+ $newStyle .= $k . ':' . $v . ';';
|
|
|
+ }
|
|
|
+ $attrArray['style'] = $newStyle;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 重建属性字符串
|
|
|
+ $newAttr = '';
|
|
|
+ foreach ($attrArray as $k => $v) {
|
|
|
+ $newAttr .= ' ' . $k . '="' . htmlspecialchars($v, ENT_QUOTES, 'UTF-8') . '"';
|
|
|
+ }
|
|
|
+ return '<' . $tag . $newAttr . '>';
|
|
|
+ }, $html);
|
|
|
+ }
|
|
|
}
|