wp_parse_list()WP 5.1.0

Cleans up an array, comma- or space-separated list of scalar values.

1 time — 0.000001 sec (speed of light) | 50000 times — 0.04 sec (speed of light) | PHP 7.2.16, WP 5.1.1

No Hooks.

Return

Array. Array of values.

Usage

wp_parse_list( $list );
$list(array|string) (required)
List of values.

Examples

0

#1 Demo

$str_ids = ",1  2  , foo   4 bar,   6 \n /asd/asd \r\n [email protected]#$ \t tab";
$ids = wp_parse_list( $str_ids );

/*
Array
(
	[0] => 1
	[1] => 2
	[2] => foo
	[3] => 4
	[4] => bar
	[5] => 6
	[6] => /asd/asd
	[7] => [email protected]#$
	[8] => tab
)
*/
$str  = 'M-11, М-11 some:val «Μόσχα - Αγία Πετρούπολη», വൈശ്യി, ഗാസേൽ';
$list = wp_parse_list( $str );

/*
Array
(
	[0] => M-11
	[1] => М-11
	[2] => some:val
	[3] => «Μόσχα
	[4] => -
	[5] => Αγία
	[6] => Πετρούπολη»
	[7] => വൈശ്യി
	[9] => ഗാസേൽ
)
*/
$str  = '
First line
Second
Third
';
$list = wp_parse_list( $str );

/*
Array
(
	[0] => First
	[1] => line
	[2] => Second
	[3] => Third
)
*/

A string with no data or an empty string:

$ids = wp_parse_list( ',' ); // array( )
$ids = wp_parse_list( '' );  // array( )

An array will return unchanged:

$arr = [ 'foo', 5, '', 'bar' ];
$parsed = wp_parse_list( $arr );

/*
Array
(
	[0] => foo
	[1] => 5
	[2] =>
	[3] => bar
)
*/

Changelog

Since 5.1.0 Introduced.

wp_parse_list() code WP 6.1.1

function wp_parse_list( $list ) {
	if ( ! is_array( $list ) ) {
		return preg_split( '/[\s,]+/', $list, -1, PREG_SPLIT_NO_EMPTY );
	}

	// Validate all entries of the list are scalar.
	$list = array_filter( $list, 'is_scalar' );

	return $list;
}