简体   繁体   中英

How do you split a string of pipe separated values and return an array?

I have an array like the following:

array(1) {
[0]=>
string(160)     "|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|"
}

I'm trying to find a way to strip the pipes and turn them each into an array.

Here's the code that will output the results.

<?php 
if( in_array( 'gb',     get_field('rights_management_control_by_continent_europe') ) or 'gb' ==     get_field('rights_management_control_by_continent') ) {
?>   

STUFF HERE

<?php } ?>

And just out of curiosity, is this doable in JavaScript?

In Javascript you can split string to array by using

s = "a|b|c"
arr = s.split('|') 

//access your array
arr[0]
arr[1]
.....

Use the PHP explode tag.

<?php
$arr = ["|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|"];
$pieces = explode("|", $arr[0]);

Each item separated by the pipe symbol would be a new item in the away, with ad being [1] as you start with a pipe.

[ and ] can start and close an array

So you have this array, I'll just put it in a variable $old_array :

$old_array = array(0=>"|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|");

To split the string on index 0 we use the explode function on the first element in the $old_array array:

$exploded_array = explode("|", $old_array[0]);

The variable $exploded_array will now hold an array with all the pairs of letters as separate elements:

["","ad","al","at","ax","ba","be",...]

In JavaScript it would look a little different but still similar:

var old_array = ["|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|"];

var split_array = old_array[0].split('|');

The split_array variable will contain all the pairs of letters as separate elements:

["","ad","al","at","ax","ba","be",...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM