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 = '~\*[^*]*\*~'; 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 如何修改别人网站内的数字,各位接单的私我
  • ¥15 poi怎么在指定位置之后生成多个表格
  • ¥15 nginx在location设置了client_max_body_size依旧报错413
  • ¥15 C#添加WCF服务引用客户端调用方法没有反应
  • ¥15 stm32f103c8t6与esp8266
  • ¥15 使用Hadoop的MapReduce program
  • ¥15 Python发生IndexError错误如何解决?
  • ¥15 如何用matlab搭建激光器
  • ¥15 51单片机两路互补SPWM输出全桥逆变
  • ¥15 outlook左边用户名下拉为啥打不开了