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

发布于 2024-07-29 01:14:00 字数 256 浏览 9 评论 0原文

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

事实上,可以将输入数据: 转换

[    asdf asdf     asdf           asdf   ] 

为输出数据:

[asdf asdf asdf asdf]

我该怎么做?

$data contains 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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

把回忆走一遍 2024-08-05 01:14:00

修剪、用单个空格替换制表符和多余空格:

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

Trim, replace tabs and extra spaces with single spaces:

$data = preg_replace('/[ ]{2,}|[\t]/', ' ', trim($data));
百变从容 2024-08-05 01:14:00
$data = trim(preg_replace('/\s+/g', '', $data));
$data = trim(preg_replace('/\s+/g', '', $data));
巷雨优美回忆 2024-08-05 01:14:00
$data = trim($data);

这会消除您的前导(和尾随)空格。

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

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

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

这样就摆脱了你的标签。

$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.

完美的未来在梦里 2024-08-05 01:14:00

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

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

您也许可以使用单个正则表达式来完成此操作,但它将是一个相当复杂的正则表达式。 上面的内容更加简单。

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

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".

看透却不说透 2024-08-05 01:14:00
$new_data = preg_replace("/[\t\s]+/", " ", trim($data));
$new_data = preg_replace("/[\t\s]+/", " ", trim($data));
清旖 2024-08-05 01:14:00

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

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

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

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

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

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

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

因此,我们使用模式数组和替换数组来代替模式字符串和替换字符串,这会导致多余的模式 LR 被修剪。

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.

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. 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.

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

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.

紫瑟鸿黎 2024-08-05 01:14:00

如果您也需要删除 

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

In case you need to remove   too.

$data = trim(preg_replace('/\s+|nbsp;/g', '', $data));
相思碎 2024-08-05 01:14:00

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

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

请参阅 比利诺亚

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

See billynoah

狼性发作 2024-08-05 01:14:00

只要使用这个正则表达式,

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

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

这里正则表达式中的符号 + 表示一次或多次,
模式的意思是,只要有两个或多个空格,就用一个空格替换

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文