简体   繁体   English

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

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

$data contains tabs, leading spaces and multiple spaces. $data包含制表符、前导空格和多个空格。 I wish to replace all tabs with a space.我希望用空格替换所有选项卡。 Multiple spaces with one single space, and remove leading spaces.多个空格与一个空格,并删除前导空格。

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?我该怎么做呢?

Trim, replace tabs and extra spaces with single spaces:修剪,用单个空格替换制表符和额外空格:

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

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”。

$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.这摆脱了你的标签。

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

This answer takes the question completely literally: it is only concerned with spaces and tabs.这个答案完全从字面上理解了这个问题:它只与空格和制表符有关。 Granted, the OP probably also wants to include other kinds of whitespace in what gets trimmed/compressed, but let's pretend he wants to preserve embedded CR and/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 \A and \Z escape characters to specify the beginning and end of the subject, instead of the typical ^ and $ which are line-oriented meta-characters .我们使用\A\Z转义字符来指定主题的开头和结尾,而不是典型的面向行的元字符^$ This is not so much because they are needed in this instance as much as "defensive" programming, should the value of S change to make them needed in the future.这与其说是因为在这种情况下需要它们,不如说是“防御性”编程,如果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 array than 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 L and R being trimmed.因此,我们使用的不是模式字符串和替换字符串,而是模式数组和替换数组,这会导致多余的模式LR被修剪。

In case you need to remove  如果您需要删除  too.也。

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

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 // 替换比 \s 更多的空格字符类型

See billynoah比利诺亚

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这里正则表达式中的 sign +表示一次或多次,pattern 表示,无论哪里有两个或多个空格,都用一个空格替换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM