删除句号之前的空格? str_replace

问题描述 投票:0回答:4

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

文本可能看起来像这样,并且到处都有空格。啦啦啦啦……

这是我的代码,尽管它成功删除了任何 ( ) 并将其替换为“无”:

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

有什么想法吗?

php str-replace
4个回答
7
投票

这只是扩展Moylin的答案

要将其变成 1 个查询,只需这样做:

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

正则表达式的解释:

\s 匹配空格

+ 1 次到无限次之间的匹配。

(?= ) 是正向前瞻。这意味着“您必须在主要组之后找到它,但不要包含它。”

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

\.是一个转义句点(因为 . 匹配正则表达式中的任何内容)

并且 , 是逗号!


2
投票

要删除句号

.
和逗号
,
之前的所有空格,您可以将数组传递给str_replace函数:

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

在您提供的示例中,如果句点后面没有空格,则不会删除句点之前的空格

' . '


1
投票
$output_this = preg_replace('/\s+\./', '.', $output_this);
$output_this = preg_replace('/\s+,/', ',', $output_this);

这应该是准确的。

抱歉,我不能更好地为您将其优化为单个查询。 编辑:删除了字符串末尾的 $ ,不确定您是否想要这样。


0
投票
$content = "This is , some string .";
$content = str_replace( ' .', '.',$content);
$content = str_replace( ' ,', ',',$content);
echo $content;
© www.soinside.com 2019 - 2024. All rights reserved.