PHP中用一个空格替换多个空格和换行符 [英] Replace Multiple Spaces and Newlines with only one space in PHP

查看:43
本文介绍了PHP中用一个空格替换多个空格和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个换行符的字符串.

I have a string with multiple newlines.

字符串:

This is         a dummy text.               I need              




to                                      format
this.

期望输出:

This is a dummy text. I need to format this.

我正在使用这个:

$replacer  = array("\r\n", "\n", "\r", "\t", "  ");
$string = str_replace($replacer, "", $string);

但它没有按预期/要求工作.有些单词之间没有空格.

But it is not working as desired/required. Some of the words don't have spaces between them.

实际上我需要转换字符串,所有单词用单个空格分隔.

Actually I need to convert the string with all the words separated by single spaces.

推荐答案

我鼓励你使用 preg_replace:

# string(45) "This is a dummy text . I need to format this."
$str = preg_replace( "/\s+/", " ", $str );

演示:http://codepad.org/no6zs3oo

您可能已经注意到第一个示例的 " . " 部分.后面紧跟标点符号的空格可能应该完全删除.快速修改允许这样做:

You may have noted in the " . " portion of the first example. Spaces that are immediately followed by punctuation should probably be removed entirely. A quick modification permits this:

$patterns = array("/\s+/", "/\s([?.!])/");
$replacer = array(" ","$1");

# string(44) "This is a dummy text. I need to format this."
$str = preg_replace( $patterns, $replacer, $str );

演示:http://codepad.org/ZTX0CAGD

这篇关于PHP中用一个空格替换多个空格和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆