douwen8118 2011-01-05 12:00
浏览 54
已采纳

preg_replace只有OUTSIDE标签? (...我们不是在谈论完整的'html解析',只是一点降价)

What is the easiest way of applying highlighting of some text excluding text within OCCASIONAL tags "<...>"?

CLARIFICATION: I want the existing tags PRESERVED!

$t = 
preg_replace(
  "/(markdown)/",
  "<strong>$1</strong>",
"This is essentially plain text apart from a few html tags generated with some
simplified markdown rules: <a href=markdown.html>[see here]</a>");

Which should display as:

"This is essentially plain text apart from a few html tags generated with some simplified markdown rules: see here"

... BUT NOT MESS UP the text inside the anchor tag (i.e. <a href=markdown.html> ).

I've heard the arguments of not parsing html with regular expressions, but here we're talking essentially about plain text except for minimal parsing of some markdown code.

  • 写回答

5条回答 默认 最新

  • dphphvs496524 2011-01-05 12:55
    关注

    Actually, this seems to work ok:

    <?php
    $item="markdown";
    $t="This is essentially plain text apart from a few html tags generated 
    with some simplified markdown rules: <a href=markdown.html>[see here]</a>";
    
    //_____1. apply emphasis_____
    $t = preg_replace("|($item)|","<strong>$1</strong>",$t);
    
    // "This is essentially plain text apart from a few html tags generated 
    // with some simplified <strong>markdown</strong> rules: <a href=
    // <strong>markdown</strong>.html>[see here]</a>"
    
    //_____2. remove emphasis if WITHIN opening and closing tag____
    $t = preg_replace("|(<[^>]+?)(<strong>($item)</strong>)([^<]+?>)|","$1$3$4",$t);
    
    // this preserves the text before ($1), after ($4) 
    // and inside <strong>..</strong> ($2), but without the tags ($3)
    
    // "This is essentially plain text apart from a few html tags generated
    // with some simplified <strong>markdown</strong> rules: <a href=markdown.html>
    // [see here]</a>"
    
    ?>
    

    A string like $item="odd|string" would cause some problems, but I won't be using that kind of string anyway... (probably needs htmlentities(...) or the like...)

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

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥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 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)