PHP <br/>,其中小写字母与大写字母

时间:2019-04-19 14:14:38

标签: php preg-replace preg-match preg-split

我试图将遇到大写字母的每个字符放在前面。我实现的是:

$str =  "Rating: goodHelps control sebum production Rating: averagePrevents the development of microorganisms in cosmetics Rating: badCan be allergenic Rating: badToxic to cell division"; 
$string = preg_replace('/([a-z])([A-Z])/', "</br>", $str);

print_R($string);

结果:

  

评分:go

     

麋鹿控制皮脂的产生评分:平均

     

避免化妆品中微生物的生长等级:ba

     

防过敏等级:ba

     

对细胞分裂有毒

如您所见,它删除了第一个和第二个字符。我需要带。

的全文

2 个答案:

答案 0 :(得分:1)

您想使用反向引用替换中捕获的内容。第一个捕获组()$1,第二个捕获组是$2

$string = preg_replace('/([a-z])([A-Z])/', '$1</br>$2', $str);

答案 1 :(得分:1)

您可以使用环视功能,这会在小写和大写字符之间插入</br>

$str =  "Rating: goodHelps control sebum production Rating: averagePrevents the development of microorganisms in cosmetics Rating: badCan be allergenic Rating: badToxic to cell division"; 
echo preg_replace('/(?<=[a-z])(?=[A-Z])/', "</br>", $str);

输出:

Rating: good</br>Helps control sebum production Rating: average</br>Prevents the development of microorganisms in cosmetics Rating: bad</br>Can be allergenic Rating: bad</br>Toxic to cell division
相关问题