php - 如何从 html 标签中删除属性?

标签 php html-parsing

我如何使用 php 去除标签中的所有/任何属性,比如段落标签?

<p class="one" otherrandomattribute="two"><p>

最佳答案

虽然有更好的方法,但您实际上可以使用正则表达式从 html 标签中去除参数:

<?php
function stripArgumentFromTags( $htmlString ) {
    $regEx = '/([^<]*<\s*[a-z](?:[0-9]|[a-z]{0,9}))(?:(?:\s*[a-z\-]{2,14}\s*=\s*(?:"[^"]*"|\'[^\']*\'))*)(\s*\/?>[^<]*)/i'; // match any start tag

    $chunks = preg_split($regEx, $htmlString, -1,  PREG_SPLIT_DELIM_CAPTURE);
    $chunkCount = count($chunks);

    $strippedString = '';
    for ($n = 1; $n < $chunkCount; $n++) {
        $strippedString .= $chunks[$n];
    }

    return $strippedString;
}
?>

上面的内容可能用更少的字符写,但它完成了工作(快速而肮脏)。

关于php - 如何从 html 标签中删除属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/770219/

相关文章:

php - MySQL:从最新行的列中检索值

php - 如何在导航栏 CSS 和 HTML 上方显示图像

javascript - 使用 async 和 defer 按顺序加载脚本

python - BeautifulSoup页面抓取时出现KeyError

php - 为什么 strtotime (' ' ) 和 strtotime ('.' ) 返回时间戳?

javascript - ajax数据显示在10行的表格中

php - 将 PHP 编译为静态二进制文件

php - 如何在 PHP 中使用黑名单去除 HTML 标签?

c - 如何使用 libcurl 登录安全网站并获取登录后的 html

javascript - 如何解决解析 HTML 时出现错误