¿Cómo puedo explotar y recortar espacios en blanco?


Por ejemplo, me gustaría crear un array a partir de los elementos de esta cadena:

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

Sé que puedes explotar y recorrer a través de ellos y recortar:

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

Pero siento que hay un enfoque de una línea que puede manejar esto. Alguna idea?

Author: dreftymac, 2013-10-13

9 answers

Puede hacer lo siguiente usando array_map:

$new_arr = array_map('trim', explode(',', $str));
 336
Author: SeanWM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-13 15:42:19

Respuesta mejorada

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

Resultado:

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

Esto

  • Se divide solo en comas
  • Recorta espacios en blanco de cada elemento.
  • Ignora los elementos vacíos
  • No divide un elemento con espacios internos como "cosa verde"
 35
Author: Amr ElAdawy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-28 09:16:35

Lo siguiente también se encarga de los espacios en blanco al inicio / final de la cadena de entrada:

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

Y esta es una prueba mínima con espacios en blanco en cada posición sensible:

$str = ' first , second , third , fourth, fifth ';
$new_arr = preg_split('/\s*,\s*/', trim($str));
var_export($str);
 19
Author: Diego Perini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-02 20:11:42

También puede hacer esto con una regex de una línea

preg_split('@(?:\s*,\s*|^\s*|\s*$)@', $str, NULL, PREG_SPLIT_NO_EMPTY);
 2
Author: Dom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-01 12:14:57

Prueba esto:

$str = preg_replace("/\s*,\s*/", ",", 'red,     green,     blue ,orange');
 1
Author: Jason OOO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-13 15:45:26

ESPECÍFICAMENTE para la cadena de ejemplo del OP, ya que cada subcadena que se emparejará es una sola palabra, puede usar str_word_count().

Código: ( Demo )

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

Salida:

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

Esto también se puede adaptar para subcadenas más allá de las letras (y algunos guiones y apóstrofos if si lee la letra pequeña) agregando los caracteres necesarios al parámetro character mask / 3rd.

Código: ( Demo )

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

Salida:

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

Nuevamente, estoy tratando esta pregunta muy estrechamente debido a la cadena de muestra, pero esto proporcionará la misma salida deseada:

Código: ( Demo )

$str = ' red,     green,     blue ,orange ';
var_export(preg_match_all('/[^, ]+/',$str,$out)?$out[0]:'fail');
 0
Author: mickmackusa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-02 14:51:31

Puedes usar preg_split() para eso.

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

/* Result:
  Array
  (
      [0] => red
      [1] => green
      [2] => blue
      [3] => orange
  )
 */
 -1
Author: Sutandiono,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-13 15:49:48
$str = str_replace(" ","", $str);
 -4
Author: BlackWhite,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-13 16:01:07

Recortar y explotar

$str = 'rojo, verde, azul ,naranja';

$str = trim($str);

Str strArray = explode (',', st str);

Print_r (str strArray);

 -9
Author: Anil M Saini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-01 07:07:21