PHP </br> 小写字母遇到大写字母

PHP </br> where lower-case letters meets uppercase-letter

我试图在每个遇到大写字母的字符前加上。我取得的成绩是:

$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);

结果:

Rating: goo

elps control sebum production Rating: averag

revents the development of microorganisms in cosmetics Rating: ba

an be allergenic Rating: ba

oxic to cell division

如您所见,它删除了第一个和之后的字符。我需要带有 .

的全文

您想对替换中捕获的内容使用反向引用。第一个捕获组 ()</code>,第二个是 <code>:

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

您可以使用环视,这会在大小写字符之间插入 </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