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( $input_list );
$input_list(array|string) (required)
List of values.

Examples

0

#1 Demo

$str_ids = ",1  2  , foo   4 bar,   6 \n /asd/asd \r\n !@#$ \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] => !@#$
	[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
)
*/
0

#2 Another example of how the function works

$str = 'cookie-policy, privacy-policy, terms-and-conditions, nutritional-page,  

campaigns/tour-virtual/,   campaigns/virtual-tasting/,  campaigns/sunsetdros21uk/, 

campaigns/sunsetdros21uk/venues/, campaigns/sunsetdros21uk/terms-and-conditions/,
campaigns/sunsetdros21scotland/,

campaigns/sunsetdros21scotland/venues/,

campaigns/sunsetdros21scotland/terms-and-conditions/,
campaigns/easyjet/instant-win/,
campaigns/surveyuk21/';

$list = wp_parse_list( $str );

print_r( $list );

/*
Array
(
	[0] => cookie-policy
	[1] => privacy-policy
	[2] => terms-and-conditions
	[3] => nutritional-page
	[4] => campaigns/tour-virtual/
	[5] => campaigns/virtual-tasting/
	[6] => campaigns/sunsetdros21uk/
	[7] => campaigns/sunsetdros21uk/venues/
	[8] => campaigns/sunsetdros21uk/terms-and-conditions/
	[9] => campaigns/sunsetdros21scotland/
	[10] => campaigns/sunsetdros21scotland/venues/
	[11] => campaigns/sunsetdros21scotland/terms-and-conditions/
	[12] => campaigns/easyjet/instant-win/
	[13] => campaigns/surveyuk21/
)
*/

Changelog

Since 5.1.0 Introduced.

wp_parse_list() code WP 6.4.3

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

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

	return $input_list;
}