这是字符串
(代码)
Pivot: 96.75<br />Our preference: Long positions above 96.75 with targets @ 97.8 & 98.25 in extension.<br />Alternative scenario: Below 96.75 look for further downside with 96.35 & 95.9 as targets.<br />Comment the pair has broken above its resistance and should post further advance.<br />
(文本)
“Pivot:96.75
我们的偏好:多头头寸高于96.75,目标价位为97.8和98.25。附加情况:96.75以下进一步下行,目标为96.35和95.9。<评论该对已突破其阻力并应进一步上涨。
“
结果应为
(代码)
<b>Pivot</b>: 96.75<br /><b>Our preference</b>: Long positions above 96.75 with targets @ 97.8 & 98.25 in extension.<br /><b>Alternative scenario</b>: Below 96.75 look for further downside with 96.35 & 95.9 as targets.<br />Comment the pair has broken above its resistance and should post further advance.<br />
(文本)
Pivot :96.75
我们的偏好:多头头寸高于96.75,目标为@ 97.8&amp; 98.25在扩展中。
备选方案:在96.75以下寻找进一步下行的96.35&amp; 95.9为目标。
评论该对已突破其阻力并应进一步推进。
porpuse :
在:
签名之前包裹所有单词。
我试过这个正则表达式:((\A )|(<br />))(?P<G>[^:]*):
,但它只适用于python环境。我在PHP中需要这个:
$pattern = '/((\A)|(<br\s\/>))(?P<G>[^:]*):/';
$description = preg_replace($pattern, '<b>$1</b>', $description);
感谢。
答案 0 :(得分:2)
这个preg_replace应该可以解决这个问题:
preg_replace('#(^|<br ?/>)([^:]+):#m','$1<b>$2</b>:',$input)
PHP Fiddle - 跑步(F9)
答案 1 :(得分:1)
首先,我应该说使用适当的解析器(例如DOMDocument
)可以更好地完成HTML操作。这个特殊的问题很简单,所以正则表达式可以在没有太多hocus pocus的情况下工作,但要注意:)
您可以使用环视assertions;这使您无需在替换期间恢复相邻的字符串:
echo preg_replace('/(?<=^|<br \/>)[^:]+(?=:)/m', '<b>$0</b>', $str);
首先,后视断言匹配每行的开头或前一个<br />
。然后,匹配除冒号之外的任何字符;先行断言确保它后跟一个冒号。
/m
修饰符用于使^
与每一行的开头匹配,而不是始终与主题字符串的开头匹配的\A
。
答案 2 :(得分:1)
我能想出的最“general”和最少正则表达式的方法就是:
$parts = explode('<br', $str);//don't include space and `/`, as tags may vary
$formatted = '';
foreach($parts as $part)
{
$formatted .= preg_replace('/^\s*[\/>]{0,2}\s*([^:]+:)/', '<b>$1</b>',$part).'<br/>';
}
echo $formatted;
或者:
$formatted = array();
foreach($parts as $part)
{
$formatted[] = preg_replace('/^\s*[\/>]{0,2}\s*([^:]+:)/', '<b>$1</b>',$part);
}
echo implode('<br/>', $formatted);
测试并将其作为输出
枢轴: 96.75
我们的偏好:多头头寸高于96.75,目标价位为97.8&amp; 98.25在扩展中。
备选方案:在96.75以下寻找进一步的下行空间96.35&amp; 95.9为目标。
评论该对已突破其阻力并应进一步推进。
话虽如此,我确实发现这些数据很奇怪,如果我是你,我会考虑str_replace
或preg_replace
- 所有的休息时间PHP_EOL
:
$str = preg_replace('/\<\s*br\s*\/?\s*\>/i', PHP_EOL, $str);//allow for any form of break tag
然后,您的字符串看起来完全,如the data I had to parse, and got the regex for that here:
$str = preg_replace(...);
$formatted = preg_replace('/^([^:\n\\]++)\s{0,}:((\n(?![^\n:\\]++\s{0,}:)|.)*+)/','<b>$1:</b>$2<br/>', $str);