dqwh1201 2013-08-13 09:28
浏览 22
已采纳

用正则表达式包装字符串中的单词

This is the string

(code)

Pivot: 96.75<br />Our preference: Long positions above 96.75 with targets @ 97.8 &amp; 98.25 in extension.<br />Alternative scenario: Below 96.75 look for further downside with 96.35 &amp; 95.9 as targets.<br />Comment the pair has broken above its resistance and should post further advance.<br />

(text)

"Pivot: 96.75
Our preference: Long positions above 96.75 with targets @ 97.8 & 98.25 in extension.
Alternative scenario: Below 96.75 look for further downside with 96.35 & 95.9 as targets.
Comment the pair has broken above its resistance and should post further advance.
"



the result should be

(code)

<b>Pivot</b>: 96.75<br /><b>Our preference</b>: Long positions above 96.75 with targets @ 97.8 &amp; 98.25 in extension.<br /><b>Alternative scenario</b>: Below 96.75 look for further downside with 96.35 &amp; 95.9 as targets.<br />Comment the pair has broken above its resistance and should post further advance.<br />

(text)
Pivot: 96.75
Our preference: Long positions above 96.75 with targets @ 97.8 & 98.25 in extension.
Alternative scenario: Below 96.75 look for further downside with 96.35 & 95.9 as targets.
Comment the pair has broken above its resistance and should post further advance.



The porpuse:
Wrap all the words before : sign.

I've tried this regex: ((\A )|(<br />))(?P<G>[^:]*):, but its working only on python environment. I need this in PHP:

$pattern = '/((\A)|(<br\s\/>))(?P<G>[^:]*):/';
$description = preg_replace($pattern, '<b>$1</b>', $description);

Thanks.

  • 写回答

3条回答 默认 最新

  • duanque3125 2013-08-13 09:32
    关注

    I should start by saying that HTML operations are better done with a proper parser such as DOMDocument. This particular problem is straightforward, so regular expressions may work without too much hocus pocus, but be warned :)

    You can use look-around assertions; this frees you from having to restore the neighbouring strings during the replacement:

    echo preg_replace('/(?<=^|<br \/>)[^:]+(?=:)/m', '<b>$0</b>', $str);
    

    Demo

    First, the look-behind assertion matches either the start of each line or a preceding <br />. Then, any characters except the colon are matched; the look-ahead assertion makes sure it's followed by a colon.

    The /m modifier is used to make ^ match the start of each line as opposed to \A which always matches the start of the subject string.

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

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码