在分隔符

时间:2017-05-22 16:34:14

标签: php

我有一个字符串需要在分隔符之间给出一个空格,例如:

Oceans and lakes have much in common,but they are also quite different.

预期输出应如下:

Oceans and lakes have much in common , but they are also quite different .

我尝试过preg_replace,我只能在下一个char中给出一个空格。

这是我的代码:

$string = "Oceans and lakes have much in common,but they are also quite different." $string = preg_replace('/([\.,\?\!\:])/',"\\1 ",$string);

输出:

Oceans and lakes have much in common, but they are also quite different.

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

尝试preg_replace('/([\.\?\!\:])/'\ \,\ \"\\1 ",$string);不确定php但是在bash中你必须逃避空格。

答案 1 :(得分:1)

在替换(第二个参数)

中的\\1引用之前放置一个空格

$string = preg_replace('/([\.,\?\!\:])/'," \\1 ",$string);