正则表达式:将 After first space 替换为 in php

Regex: Replace After first space with   in php

我正在 PHP 制作 translateModel,它将在 return HTML

中发布

因此,在示例代码中,它只是将 space 替换为 ' '

preg_replace('/\s/', ' ', $myString);

但我想要的是先替换space 以此类推(不算先space)

如:

我想我找到了答案:

preg_replace('/\s(?=\s)/', ' ', $myString);

要替换除第一个空格之外的一连串空格中的每个空格,请使用

preg_replace('~(?<=\s)\s~', '&nbsp;', $myString)

regex demo

它将A B C D E变成A B C &nbsp;&nbsp;D &nbsp;&nbsp;&nbsp;&nbsp;E

您的 /\s(?=\s)/ lookahead 解决方案将替换除一连串空白中的最后一个以外的所有空白,因为正先行需要模式的存在立即当前位置的 right,整个 lookbehind 将查找与 left 的匹配项当前位置。