是否删除句点前的空格?str_replace


Remove spaces before periods ? str_replace

我试图在回显文本之前删除文本中句号之前的所有空格和逗号。

文本可以是这样的,并且到处都是空格。布拉布拉。。。

这是我的代码,尽管它成功地删除了任何()并用"什么都没有"代替:

$strip_metar = array('( )' => '', ' . ' => '. ', ' , ' => ', ');
$output_this = $text->print_pretty();
$output_this = str_replace(array_keys($strip_metar),
                           array_values($strip_metar),
                           $output_this);

有什么想法吗?

我没有50个代表,所以我不能发表评论,但这只是对Moylin的答案的扩展:

要使其成为1个查询,只需执行以下操作:

$output_this = preg_replace('/'s+(?=['.,])/', '', $output_this);

正则表达式的解释:

''s与空间匹配

+匹配范围在1到无穷多次之间。

(?=)是一个积极的展望。这意味着"你必须在主组之后找到这个,但不要包括它。"

[]是一组要匹配的字符。

''。是转义符(因为.匹配正则表达式中的任何内容)

和,是逗号!

要删除句点.和逗号,之前的所有空格,可以将数组传递给str_replace函数:

$output_this = str_replace(array(' .',' ,'),array('.',','),$string);

在您提供的示例中,如果句点后面没有空格' . '

,则不会在句点之前去掉空格
$output_this = preg_replace('/'s+'./', '.', $output_this);
$output_this = preg_replace('/'s+,/', ',', $output_this);

这应该是准确的。

对不起,我没有更好的优化为一个单一的查询为你。edit:删除了字符串末尾的$,不确定您是否希望这样。

$content = "This is , some string .";
$content = str_replace( ' .', '.',$content);
$content = str_replace( ' ,', ',',$content);
echo $content;