保留 preg_replace 找到的角色

Keep a character found by preg_replace

我想替换一个点,然后是 space,然后是大写字母,我尝试用这种模式将其替换为    :

preg_replace('/\. [A-Z]/', '.    'With marriage came a move to the beautiful Birmingham, Alabama area. Diving in head first.');

它在工作,但我首先失去了跳水的 D。

如何保留?

将字母匹配模式放入非消耗先行:

'/\.\s+(?=[A-Z])/'

\s+ 将匹配 1 个或多个 whitespaces(或者如果你不想那样,保持常规 space)并且 (?=[A-Z]) 使引擎要求大写 ASCII 字母紧跟在字符串中的当前位置之后。

查看 PHP demo 打印 With marriage came a move to the beautiful Birmingham, Alabama area.   Diving in head first.