如何在 PHP 中的变量中用空格替换制表符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1181559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:24:03  来源:igfitidea点击:

How do I replace tabs with spaces within variables in PHP?

phpreplacetabsspaces

提问by Arthur

$datacontains tabs, leading spaces and multiple spaces. I wish to replace all tabs with a space. Multiple spaces with one single space, and remove leading spaces.

$data包含制表符、前导空格和多个空格。我希望用空格替换所有选项卡。多个空格一个空格,并删除前导空格。

In fact somthing that would turn this input data:

事实上,这会改变这个输入数据:

[    asdf asdf     asdf           asdf   ] 

Into output data:

进入输出数据:

[asdf asdf asdf asdf]

How do I do this?

我该怎么做呢?

采纳答案by RaYell

$data = trim(preg_replace('/\s+/g', '', $data));

回答by ahc

Trim, replace tabs and extra spaces with single spaces:

修剪,用单个空格替换制表符和额外空格:

$data = preg_replace('/[ ]{2,}|[\t]/', ' ', trim($data));

回答by cletus

Assuming the square brackets aren't part of the string and you're just using them for illustrative purposes, then:

假设方括号不是字符串的一部分,并且您只是出于说明目的使用它们,那么:

$new_string = trim(preg_replace('!\s+!', ' ', $old_string));

You might be able to do that with a single regex but it'll be a fairly complicated regex. The above is much more straightforward.

您可能可以使用单个正则表达式来做到这一点,但这将是一个相当复杂的正则表达式。上面的就简单多了。

Note:I'm also assuming you don't want to replace "AB\t\tCD" (\t is a tab) with "AB CD".

注意:我还假设您不想将“AB\t\tCD”(\t 是制表符)替换为“AB CD”。

回答by Gabriel Hurley

$data = trim($data);

That gets rid of your leading (and trailing) spaces.

这摆脱了您的前导(和尾随)空格。

$pattern = '/\s+/';
$data = preg_replace($pattern, ' ', $data);

That turns any collection of one or more spaces into just one space.

这会将一个或多个空间的任何集合变成一个空间。

$data = str_replace("\t", " ", $data);

That gets rid of your tabs.

这摆脱了你的标签。

回答by slosd

$new_data = preg_replace("/[\t\s]+/", " ", trim($data));

回答by Jeff

This answer takes the question completely literally: it is onlyconcerned with spaces and tabs. Granted, the OP probablyalso wants to include other kinds of whitespace in what gets trimmed/compressed, but let's pretend he wants to preserve embedded CRand/or LF.

这个答案完全从字面上理解了这个问题:它只涉及空格和制表符。当然,OP可能还希望在修剪/压缩的内容中包含其他类型的空格,但让我们假设他想保留嵌入的CR和/或LF.

First, let's set up some constants. This will allow for both ease of understanding and maintainability, should modifications become necessary. I put in some extra spaces so that you can compare the similarities and differences more easily.

首先,让我们设置一些常量。如果需要修改,这将允许易于理解和可维护性。我添加了一些额外的空格,以便您可以更轻松地比较异同。

define( 'S', '[ \t]+'      ); # Stuff you want to compress; in this case ONLY spaces/tabs
define( 'L', '/\A'.S.'/'   ); # stuff on the Left edge will be trimmed
define( 'M',   '/'.S.'/'   ); # stuff in the Middle will be compressed
define( 'R',   '/'.S.'\Z/' ); # stuff on the Right edge will be trimmed
define( 'T', ' '           ); # what we want the stuff compressed To

We are using \Aand \Zescape charactersto specify the beginning and end of the subject, instead of the typical ^and $which are line-oriented meta-characters. This is not so much because they are needed in this instance as much as "defensive" programming, should the value of Schange to make them needed in the future.

我们使用\A\Z转义字符来指定主题的开始和结束,而不是典型的^$面向行的元字符。这与其说是因为在这种情况下需要它们,不如说是“防御性”编程,如果S更改的价值使将来需要它们。

Now for the secret sauce: we are going to take advantage of some special semantics of preg_replace, namely (emphasis added)

现在是秘密武器:我们将利用preg_replace的一些特殊语义,即(强调)

If there are fewer elements in the replacement arraythan in the pattern array, any extra patterns will be replaced by an empty string.

如果替换数组中的元素少于模式数组中的元素,则任何额外的模式都将被空字符串替换。

function trim_press( $data ){
    return preg_replace( [ M, L, R ], [ T ], $data );
}

So instead of a pattern string and replacement string, we are using a pattern array and replacement array, which results in the extra patterns Land Rbeing trimmed.

因此,而不是一个模式字符串和替换字符串,我们用图案阵列和阵列更换,这导致额外的图案LR被修剪。

回答by Ivo Pereira

In case you need to remove  too.

如果您也需要删除 

$data = trim(preg_replace('/\s+|nbsp;/g', '', $data));

回答by will

After much frustration I found this to be the best solution, as it also removes non breaking spaces which can be two characters long:

经过多次挫折,我发现这是最好的解决方案,因为它还删除了可以是两个字符长的不间断空格:

$data = html_entity_decode(str_replace(' ',' ',htmlentities($data))); $data = trim(preg_replace('/\h/', ' ', $data));// replaces more space character types than \s

$data = html_entity_decode(str_replace(' ',' ',htmlentities($data))); $data = trim(preg_replace('/\h/', ' ', $data));// 替换比 \s 更多的空格字符类型

See billynoah

比利诺亚

回答by dav

Just use this regex

只需使用此正则表达式

$str = trim(preg_replace('/\s\s+/', ' ', $str));

it will replace all tabs and spaces by one space,

它将用一个空格替换所有制表符和空格,

here sign +in regex means one or more times, pattern means, that wherever there are two or more spaces, replace it by one space

此处登录+正则表达式表示一次或多次,模式表示,只要有两个或多个空格,就用一个空格替换它