用PHP替换多余的空格和换行符? [英] Replace excess whitespaces and line-breaks with PHP?

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

问题描述

$string = "My    text       has so    much   whitespace    




Plenty of    spaces  and            tabs";

echo preg_replace("/\s\s+/", " ", $string);

我阅读了PHP的文档,并遵循了preg_replace的教程,但是此代码产生了

我的文本有很多空格,很多空格和制表符

如何将其转换为:

我的文字有太多空格
大量的空格和制表符

解决方案

首先,我想指出的是,根据操作系统的不同,新行可以是\ r,\ n或\ r \ n. /p>

我的解决方案:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/[\r\n]+/', "\n", $string));

如有必要,可以将其分为两行:

$string = preg_replace('/[\r\n]+/', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

更新:

一个更好的解决方案是:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/\s*$^\s*/m', "\n", $string));

或者:

$string = preg_replace('/\s*$^\s*/m', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

我更改了使多行分解为单个行的正则表达式.它使用"m"修饰符(使^和$匹配新行的开头和结尾),并删除作为字符串结尾和开头的所有\ s(空格,制表符,新行,换行符)字符下一个.这解决了除了空格以外什么都没有的空行的问题.在我之前的示例中,如果一行填充了空格,那么它会跳过多余的一行.

$string = "My    text       has so    much   whitespace    




Plenty of    spaces  and            tabs";

echo preg_replace("/\s\s+/", " ", $string);

I read the PHP's documentation and follow the preg_replace's tutorial, however this code produce

My text has so much whitespace Plenty of spaces and tabs

How can I turn it into :

My text has so much whitespace
Plenty of spaces and tabs

解决方案

First, I'd like to point out that new lines can be either \r, \n, or \r\n depending on the operating system.

My solution:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/[\r\n]+/', "\n", $string));

Which could be separated into 2 lines if necessary:

$string = preg_replace('/[\r\n]+/', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

Update:

An even better solutions would be this one:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/\s*$^\s*/m', "\n", $string));

Or:

$string = preg_replace('/\s*$^\s*/m', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

I've changed the regular expression that makes multiple lines breaks into a single better. It uses the "m" modifier (which makes ^ and $ match the start and end of new lines) and removes any \s (space, tab, new line, line break) characters that are a the end of a string and the beginning of the next. This solve the problem of empty lines that have nothing but spaces. With my previous example, if a line was filled with spaces, it would have skipped an extra line.

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

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