2

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

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

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

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

有任何想法吗?

4

4 回答 4

7

我没有 50 个代表,所以我无法发表评论,但这只是为了扩展 Moylin 的回答:

要使其成为 1 个查询,只需这样做:

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

正则表达式的解释:

\s 匹配一个空格

+ 匹配 1 次和无限次。

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

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

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

和 , 是一个逗号!

于 2013-07-30T19:04:51.453 回答
2

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

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

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

于 2013-07-30T18:36:08.393 回答
1
$output_this = preg_replace('/\s+\./', '.', $output_this);
$output_this = preg_replace('/\s+,/', ',', $output_this);

这应该是准确的。

抱歉,我最好将其优化为一个查询。编辑:删除了字符串结尾的 $,不确定你是否想要这样。

于 2013-07-30T18:48:36.917 回答
0
$content = "This is , some string .";
$content = str_replace( ' .', '.',$content);
$content = str_replace( ' ,', ',',$content);
echo $content;
于 2013-07-30T18:40:09.393 回答