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条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件