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 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗