php 我怎样才能爆炸和修剪空白?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19347005/
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 19:20:19  来源:igfitidea点击:

How can I explode and trim whitespace?

phpexplodetrimhigher-order-functions

提问by SeanWM

For example, I would like to create an array from the elements in this string:

例如,我想从这个字符串中的元素创建一个数组:

$str = 'red,     green,     blue ,orange';

I know you can explode and loop through them and trim:

我知道你可以爆炸并遍历它们并修剪:

$arr = explode(',', $str);
foreach ($arr as $value) {
    $new_arr[] = trim($value);
}

But I feel like there's a one line approach that can handle this. Any ideas?

但我觉得有一种方法可以解决这个问题。有任何想法吗?

回答by SeanWM

You can do the following using array_map:

您可以使用array_map执行以下操作:

$new_arr = array_map('trim', explode(',', $str));

回答by Amr ElAdawy

An Improved answer

改进的答案

preg_split ('/(\s*,*\s*)*,+(\s*,*\s*)*/', 'red,     green thing ,,  ,,   blue ,orange');

Result:

结果:

Array
(
    [0] => red
    [1] => green thing
    [2] => blue
    [3] => orange
)

This

这个

  • Splits on commas only
  • Trims white spaces from each item.
  • Ignores empty items
  • Does not split an item with internal spaces like "green thing"
  • 仅在逗号上拆分
  • 从每个项目中修剪空白。
  • 忽略空项目
  • 不会拆分带有内部空间的项目,例如“绿色东西”

回答by Diego Perini

The following also takes care of white-spaces at start/end of the input string:

下面还处理输入字符串开头/结尾的空格:

$new_arr = preg_split('/\s*,\s*/', trim($str));

and this is a minimal test with white-spaces in every sensible position:

这是在每个合理位置都有空格的最小测试:

$str = ' first , second , third , fourth, fifth ';
$new_arr = preg_split('/\s*,\s*/', trim($str));
var_export($str);

回答by shmurf

By combining some of the principals in the existing answers I came up with

通过结合现有答案中的一些原则,我想出了

preg_split ('/\s*,+\s*/', 'red,     green thing ,,  ,,   blue ,orange', NULL, PREG_SPLIT_NO_EMPTY);

The reasoning behind it is that I found a bug in this answer, where if there is a comma at the end of the string it'll return a blank element in the array. i.e.

其背后的原因是我在此答案中发现了一个错误,如果字符串末尾有逗号,它将返回数组中的空白元素。IE

preg_split ('/(\s*,*\s*)*,+(\s*,*\s*)*/', 'red,     green thing ,,  ,,   blue ,orange,');

Results in

结果是

Array
(
  [0] => red
  [1] => green thing
  [2] => blue
  [3] => orange
  [4] => ''
)

You can fix this by using PREG_SPLIT_NO_EMPTYas mentioned in this answerto remove it, but once you are doing that there is technically no need to remove consecutive commas via the regex, thus the shortened expression

您可以通过使用本答案中提到的PREG_SPLIT_NO_EMPTY将其删除来解决此问题,但是一旦您这样做,技术上就不需要通过正则表达式删除连续的逗号,因此缩短了表达式

回答by Amit Sharma

this how you replace and explode in a single line of code

这是你如何在一行代码中替换和爆炸

$str = 'red,     green,     blue ,orange';

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

will output the results as

将输出结果为

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => orange
)

回答by Dom

You can also do this with a one line regex

你也可以用一行正则表达式来做到这一点

preg_split('@(?:\s*,\s*|^\s*|\s*$)@', $str, NULL, PREG_SPLIT_NO_EMPTY);

回答by mickmackusa

SPECIFICALLYfor the OP's sample string, because each substring to be matched is a single word, you can use str_word_count().

特别是对于 OP 的示例字符串,因为要匹配的每个子字符串都是一个单词,所以您可以使用str_word_count()

Code: (Demo)

代码:(演示

$str = ' red,     green,     blue ,orange ';
var_export(str_word_count($str,1));  // 1 means return all words in an indexed array

Output:

输出:

array (
  0 => 'red',
  1 => 'green',
  2 => 'blue',
  3 => 'orange',
)

This can also be adapted for substrings beyond letters (and some hyphens and apostrophes -- if you read the fine print) by adding the necessary characters to the character mask / 3rd parameter.

通过将必要的字符添加到字符掩码/第三个参数,这也可以适用于字母以外的子字符串(以及一些连字符和撇号——如果你阅读了细则)。

Code: (Demo)

代码:(演示

$str = " , Number1 ,     234,     0 ,4heaven's-sake  ,  ";
var_export(str_word_count($str,1,'0..9'));

Output:

输出:

array (
  0 => 'Number1',
  1 => '234',
  2 => '0',
  3 => '4heaven\'s-sake',
)


Again, I am treating this question very narrowly because of the sample string, but this will provide the same desired output:

同样,由于示例字符串,我非常狭隘地处理这个问题,但这将提供相同的所需输出:

Code: (Demo)

代码:(演示

$str = ' red,     green,     blue ,orange ';
var_export(preg_match_all('/[^, ]+/',$str,$out)?$out[0]:'fail');

回答by Jason OOO

try this:

尝试这个:

$str = preg_replace("/\s*,\s*/", ",", 'red,     green,     blue ,orange');

回答by Sutandiono

You can use preg_split()for that.

您可以为此使用preg_split()

$bar = preg_split ('/[,\s]+/', $str);
print_r ($bar);

/* Result:
  Array
  (
      [0] => red
      [1] => green
      [2] => blue
      [3] => orange
  )
 */

回答by BlackWhite

$str = str_replace(" ","", $str);