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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号