PHP 简单 html DOM 从 html 标签中删除所有属性
PHP simple html DOM remove all attributes from an html tag
$html = file_get_html('page.php');
foreach($html->find('p') as $tag_name)
{
$attr = substr($tag_name->outertext,2,strpos($tag_name->outertext, ">")-2);
$tag_name->outertext = str_replace($attr, "", $tag_name->outertext);
}
echo $html->innertext;
以上是我编写的代码,用于获取我的 html 页面中所有 <p>
标签内的内容并将其删除。
我的 html 代码与此类似:
<p class="..." id = "..." style = "...">some text...</p>
<p class="..." id = "..." style = "...">some text...</p>
<p class="..." id = "..." style = "...">some text...</p>
<font>
<p class="..." id = "..." style = "...">some text ...</p>
<p class="..." id = "..." style = "...">some text ...</p>
</font>
<p class="..." id = "..." style = "...">some text...</p>
如果我 运行 php 代码,结果将是这样的:
<p>some text...</p>
<p>some text...</p>
<p>some text...</p>
<font>
<p class="..." id = "..." style = "...">some text ...</p>
<p class="..." id = "..." style = "...">some text ...</p>
</font>
<p>some text...</p>
它不会删除 <p>
内的标签属性 <font>
。
如果有人可以帮助我,我将不胜感激。
当我使用您的代码和示例 HTML 时,它 会 从所有 <p>
标签中删除所有属性,甚至 <font>
,所以我不确定为什么你的不工作。
但看起来 simplehtmldom has methods 专门处理属性,因此您不必使用字符串函数:
$html = file_get_html('page.php');
foreach($html->find('p') as $p) {
foreach ($p->getAllAttributes() as $attr => $val) {
$p->removeAttribute($attr);
}
}
echo $html->innertext;
希望这样会更有效。
$html = file_get_html('page.php');
foreach($html->find('p') as $tag_name)
{
$attr = substr($tag_name->outertext,2,strpos($tag_name->outertext, ">")-2);
$tag_name->outertext = str_replace($attr, "", $tag_name->outertext);
}
echo $html->innertext;
以上是我编写的代码,用于获取我的 html 页面中所有 <p>
标签内的内容并将其删除。
我的 html 代码与此类似:
<p class="..." id = "..." style = "...">some text...</p>
<p class="..." id = "..." style = "...">some text...</p>
<p class="..." id = "..." style = "...">some text...</p>
<font>
<p class="..." id = "..." style = "...">some text ...</p>
<p class="..." id = "..." style = "...">some text ...</p>
</font>
<p class="..." id = "..." style = "...">some text...</p>
如果我 运行 php 代码,结果将是这样的:
<p>some text...</p>
<p>some text...</p>
<p>some text...</p>
<font>
<p class="..." id = "..." style = "...">some text ...</p>
<p class="..." id = "..." style = "...">some text ...</p>
</font>
<p>some text...</p>
它不会删除 <p>
内的标签属性 <font>
。
如果有人可以帮助我,我将不胜感激。
当我使用您的代码和示例 HTML 时,它 会 从所有 <p>
标签中删除所有属性,甚至 <font>
,所以我不确定为什么你的不工作。
但看起来 simplehtmldom has methods 专门处理属性,因此您不必使用字符串函数:
$html = file_get_html('page.php');
foreach($html->find('p') as $p) {
foreach ($p->getAllAttributes() as $attr => $val) {
$p->removeAttribute($attr);
}
}
echo $html->innertext;
希望这样会更有效。