Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从指定的html标记中删除类/样式/垃圾_Php_Regex - Fatal编程技术网

Php 从指定的html标记中删除类/样式/垃圾

Php 从指定的html标记中删除类/样式/垃圾,php,regex,Php,Regex,使用PHP和Regex,如何从标记中去除所有不需要的样式、类或其他垃圾 例如: 我希望它可以处理我设置为$tagType的任何标记类型 需要在PHP-我做它的服务器端。谢谢。如果只想针对特定的标记,则需要动态调整正则表达式,请确保在$tagType参数中使用以避免允许正则表达式匹配 与上一个答案相比,以下功能将在不太严格的标记限制下工作,例如,在功能代码之后尝试测试 function cleanTag($html, $tagType = 'div') { if ($tagType) {

使用PHP和Regex,如何从标记中去除所有不需要的样式、类或其他垃圾

例如:

我希望它可以处理我设置为
$tagType
的任何标记类型


需要在PHP-我做它的服务器端。谢谢。

如果只想针对特定的标记,则需要动态调整正则表达式,请确保在
$tagType
参数中使用以避免允许正则表达式匹配

与上一个答案相比,以下功能将在不太严格的标记限制下工作,例如,在功能代码之后尝试测试

function cleanTag($html, $tagType = 'div') {
    if ($tagType) {
        // match specific tag
        $tagType = preg_quote($tagType);
    } else {
        // match all tags
        $tagType = '[\w\d]+';
    }

    return preg_replace("/<\s*($tagType).*?>/si", '<$1>', $html);
}
函数cleanTag($html,$tagType='div'){
如果($tagType){
//匹配特定标记
$tagType=preg_quote($tagType);
}否则{
//匹配所有标签
$tagType='[\w\d]+';
}
返回preg_replace(“//si”,“”,$html);
}

文字说明:

  • /
  • 匹配零个或多个字符,直到找到结束标记
  • /si
    点字符匹配新行和不敏感比较

字符串用新标记替换整个匹配项,新标记包含捕获的标记
$1

其他可能的重复项:或。并查看相关部分以了解更多信息。
function cleanTag($html, $tagType='div'){
  $html = // regex to clean out all tags of $tagType in $html
  return $html;
}
function cleanTag($html, $tagType = 'div') {
    if ($tagType) {
        // match specific tag
        $tagType = preg_quote($tagType);
    } else {
        // match all tags
        $tagType = '[\w\d]+';
    }

    return preg_replace("/<\s*($tagType).*?>/si", '<$1>', $html);
}