douwen1929 2014-02-28 09:13
浏览 79
已采纳

在其他文本中使用preg_replace()作为后缀和后缀

I've been trying to make a mini markup parser similar to Markdown in PHP. The input looks like this:

Some text **that is bold!** and some other text

into

Some text <b>that is bold!</b> and some other text

I've found countless resources on how to replace a chunk of text with another, but only one that actually replaces suffix and postfix: this answer. After messing around with it a bit it looks like this:

$s=preg_quote("**");

$in = preg_replace(
    array('%'.$s.'-%', '%-%', '%'.$s.'%'), 
    array('<b>','_','</b>'),
    $in);

Earlier attempts are equally clumsy. It's obvious I don't really get regex or that engine's syntax so I'm at a loss. The alternative is to hack the string into pieces and add/remove what I need, but regex seems much more elegant. Any ideas?


Fix: Earlier I wrote $s=preg_quote($s) by mistake, corrected to $s=preg_quote("**")

  • 写回答

3条回答 默认 最新

  • dongzhunqiu4841 2014-02-28 09:20
    关注

    You should use a basic '\*\*(.+?)\*\*' regex.

    $s = preg_replace(
        '/\*\*(.+?)\*\*/isU',
        '<b>$1</b>',
        $s);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据