[英]Replace spaces around punctuation in PHP
I'm trying to replace trailing spaces around punctuation marks in PHP with matched punctuation followed by a single space. 我正在尝试用PHP中的标点符号替换尾随空格,并使用匹配的标点符号,后跟单个空格。
For example "Hello , I am here ! Not anymore. .. "
should become "Hello, I am here! Not anymore... "
. 例如
"Hello , I am here ! Not anymore. .. "
应该变成"Hello, I am here! Not anymore... "
。 I'm trying to use a regular expressions with a reference 我正在尝试使用带引用的正则表达式
PHP PHP
$string = preg_replace('/\s*[[:punct:]]\s*/', '$2 ', $string);
But the snippet removes punctuations: "Hello I am here Not anymore"
. 但是片段删除了标点符号:
"Hello I am here Not anymore"
。
What am I missing? 我错过了什么?
This should work for you: 这应该适合你:
<?php
$string = "Hello , I am here ! Not anymore. .. ";
echo $string = preg_replace('/(\s*)([[:punct:]])(\s*)/', '$2 ', $string);
?>
Output: 输出:
Hello, I am here! Not anymore. . .
You don't capture anything and then you try to replace with the second capture group that doesn't exist. 您没有捕获任何内容,然后尝试替换不存在的第二个捕获组。 Try a capture group
()
and then use it $1
: 尝试捕获组
()
,然后使用$1
:
$string = preg_replace('/\s*([[:punct:]])\s*/', '$1 ', $string);
In order to substitute . . .
为了替代
. . .
. . .
with ...
, this is what I'd do: 与
...
,这就是我要做的:
$string = "Hello , I am here ! Not anymore. . . ";
$string = preg_replace('/\s+(?=\pP)|(?<=\pP\s)\s+/', '', $string);
echo $string;
Output: 输出:
Hello, I am here! Not anymore...
\\pP
is the unicode property for punctuation, see the doc . \\pP
是标点符号的unicode属性, 请参阅doc 。
(?= )
is a positive look ahead (?= )
是一个积极的展望
and (?<= )
a positive look behind, see the doc . 和
(?<= )
背后的正面看, 请参阅文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.