【问题标题】:Regex to remove all inline HTML properties except colspan (PHP) [duplicate]正则表达式删除除 colspan (PHP)之外的所有内联 HTML 属性 [重复]
【发布时间】:2017-08-29 12:26:06
【问题描述】:

我有一个包含 (n) 个 HTML 页面的字符串。我只需要

和 中的内容,并且想要删除除 colspan 之外的所有内联 HTML 属性。这是我取得的成果(仍然删除了 colspan 属性):
<?php
$html = 'CURL GET THE HTML (mostly just tables)';

// Remove HTML comments, JavaScript content, CSS and not needed HTML tags
$pregReplacePattern = array(
    '/<!--(.*)-->/Uis',
    '#<.*?!DOCTYPE.*?>#i',
    '#<.*?html.*?>#i',
    '#<.*?head.*?>#i',
    '#<title.*?>.*?</title>#i',
    '#<.*?meta.*?>#i',
    '#<script.*?>.*?</script#i',
    '#<.*?link.*?>#i',
    '#<.*?body.*?>#i',
    '#<.*?form.*?>#i',
    '#<img.*?>#i',
    '"/<img[^>]+\>/i"',
);
$pregReplaceTo = array_fill_keys(
    range(0, count($pregReplacePattern) - 1), ''
);
$html = preg_replace($pregReplacePattern, $pregReplaceTo, $html);

// Remove inline HTML properties (all of them)
$html = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i", '<$1$2>', $html);

你们中的任何人都可以帮助我吗?

提前谢谢...

【问题讨论】:

  • 所以你只需要&lt;table&gt;&lt;/table&gt; (s) ?
  • 不完全是。我需要 body 标记内的所有内容,但这些大多只是具有大量内联 HTML 属性的表格。我想删除除 colspan 之外的这些属性。

标签: php html regex preg-replace


【解决方案1】:

也许你应该只在你的 php 中使用 echo 语句,而不用担心正则表达式。这就是我的意思:

<?php
echo "// Remove HTML comments, JavaScript content, CSS and not needed HTML 
tags
$pregReplacePattern = array(
'/<!--(.*)-->/Uis',
'#<.*?!DOCTYPE.*?>#i',
'#<.*?html.*?>#i',
'#<.*?head.*?>#i',
'#<title.*?>.*?</title>#i',
'#<.*?meta.*?>#i',
'#<script.*?>.*?</script#i',
'#<.*?link.*?>#i',
'#<.*?body.*?>#i',
'#<.*?form.*?>#i',
'#<img.*?>#i',
'"/<img[^>]+\>/i"',
);
$pregReplaceTo = array_fill_keys(
range(0, count($pregReplacePattern) - 1), ''
);
$html = preg_replace($pregReplacePattern, $pregReplaceTo, $html);

// Remove inline HTML properties (all of them)
$html = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i", '<$1$2>', $html);";
?>

在 IE 9.1 上运行良好

【讨论】:

    猜你喜欢
    • 2016-01-10
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2010-10-16
    • 2019-04-15
    • 2020-12-04
    • 2015-05-10
    相关资源
    最近更新 更多