dsymx68408 2014-09-01 15:53
浏览 25
已采纳

如何使用preg_replace regex将*转换为HTML

I have paragraphs of texts with this kind of markup in them:

text1 *text2* text3

I need to turn them into

text1 <strong>text2</strong> text3

I tried this code

$pattern = '~\*(.*)\*~'; 
$replacement = '<strong>\1</strong>'; 
$str = preg_replace($pattern, $replacement, $str);

It doesn't recognize the second, closing asterisk. The closing strong" html tag only appears at the next (third) asterisk much later in the same text.

What am I missing?

Update: Avinash's pattern worked for the issue, but here is a related one

I used the same pattern (the first of the two) to replace underscores with tags. But the same paragraphs included images with syntax like <img src="/my_image.jpg" width="700" height="300"> How do I avoid this regex turning those underscores? (The width/height numbers vary, not constant.)

E.g. from a text like this

Lorem ipsum dolor sit amet, <img src="/my_image.jpg" width="700" height="300">  adipiscing elit. _Fusce pharetra_ a dui nec interdum. 

I would like to get this

Lorem ipsum dolor sit amet, <img src="/my_image.jpg" width="700" height="300">  adipiscing elit. <em>Fusce pharetra</em> a dui nec interdum.
  • 写回答

1条回答 默认 最新

  • doutan8601 2014-09-01 15:54
    关注

    You need to add the quantifier ? after * which was present inside the capturing group to do a shortest possible match,

    $pattern = '~\*(.*?)\*~'; 
    

    OR

    $pattern = '~\*[^*]*\*~'; 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程