用正则表达式将单词包装成字符串


wrap words in string with regex

这是字符串

(代码)

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 />

(文本)

"枢轴:96.75
我们的偏好:96.75以上的多头仓位,目标为97.8和98.25。
替代方案:96.75以下的空头仓位,以96.35和95.9为目标,寻找进一步的下跌。
Comment该对已突破其阻力,应该会进一步上涨。"



结果应该是

(代码)

<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)
数据透视:96.75
我们的偏好:96.75以上的多头仓位,目标@97.8&98.25
替代方案:低于96.75,以96.35&95.9作为目标
评论这对组合已经突破了阻力,应该进一步推进



海豚:
:符号前的所有单词换行。

我尝试过这个regex:(('A )|(<br />))(?P<G>[^:]*):,但它只适用于python环境。我需要这个在PHP:

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

谢谢。

这个preg_replace应该可以做到:

preg_replace('#(^|<br ?/>)([^:]+):#m','$1<b>$2</b>:',$input)

PHP Fiddle-Run(F9)

我首先应该说,HTML操作最好使用合适的解析器(如DOMDocument)来完成。这个特殊的问题很简单,所以正则表达式可能在没有太多恶作剧的情况下工作,但请注意:)

您可以使用环视断言;这使您在替换过程中不必恢复相邻的字符串:

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

演示

首先,look-behind断言匹配每一行的开头或前面的<br />。然后,匹配除冒号以外的任何字符;前瞻性断言确保后面跟一个冒号。

/m修饰符用于使^与每行的开头匹配,而'A总是与主题字符串的开头匹配。

我能想到的最"通用"和最便宜的regex方法是:

$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
我们的偏好:目标在97.8&98.25
替代方案:低于96.75,以96.35&95.9作为目标
评论这对组合已经突破了阻力,应该进一步推进

话虽如此,我确实觉得这一点数据很奇怪,如果我是你,我会考虑str_replacepreg_replace使用PHP_EOL:进行所有中断

$str = preg_replace('/'<'s*br's*'/?'s*'>/i', PHP_EOL, $str);//allow for any form of break tag

然后,您的字符串看起来与我必须解析的数据完全一样,并在此处获得正则表达式:

$str = preg_replace(...);
$formatted = preg_replace('/^([^:'n'']++)'s{0,}:(('n(?![^'n:'']++'s{0,}:)|.)*+)/','<b>$1:</b>$2<br/>', $str);