dsb0003795 2013-09-19 14:11
浏览 39
已采纳

使用php regex从html标记元素中删除属性

Would like to remove any attribute within html tags and I think this can be achieved using regex but I'm not good at using regex.

Tried working with str_replace but it's just not the right way to go. And I've searched for questions similar to this but could not find any.

Example:

Got html tags like this within a variable:

$str = '
<p class="class_style" style="font-size: medium; line-height: normal; letter-spacing: normal;">content</p>
<span class="another_class_style" style="font-size: medium; line-height: normal; letter-spacing: normal;">content</span>
<ul class="another_class_style" style="background:#006;"></ul>
<li class="another_class_style" style=" list-style:circle; color:#930;">content</li>';

Call to certain preg_match()

$new_str = preg_match('', $str)

Expected Output:

$new_str = '
<p>content</p>
<span>content</span>
<ul></ul>
<li>content</li>';

Pls note that I dont intend to strip off the html tags, rather i just need to remove any tag elements within the tags.

php strip_tags() isn't an option

Would be grateful getting help with this.

  • 写回答

3条回答 默认 最新

  • dousong8187 2013-09-19 14:19
    关注
    $str = '
    <p class="class_style" style="font-size: medium; line-height: normal; letter-spacing: normal;">content</p>
    <span class="another_class_style" style="font-size: medium; line-height: normal; letter-spacing: normal;">content</span>
    <ul class="another_class_style" style="background:#006;"></ul>
    <li class="another_class_style" style=" list-style:circle; color:#930;">content</li>';
    
    $clean = preg_replace('/ .*".*"/', '', $str);
    
    echo $clean;
    

    Will return:

    <p>content</p>
    <span>content</span>
    <ul></ul>
    <li>content</li>
    

    But please don't use regex for parsing HTML, use a DOM parser.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了