$str = "colors:black;white;transparent;pink;";
list($label, $optionsStr) = explode(":", $str);
$optionsStr = rtrim($optionsStr, ";");
$options = explode(";", $optionsStr);
echo "<pre>";
print_r($label);
print_r($options);
PHP explode array with 2 types of separators
题
I have this options array:
string(111) "colors:black;white;transparent;pink;"
how can I explode it so I get as a label first separator : and the rest in array as options? I have this so far:
$options= explode(";",$rows[0]);
$htm= '<ul class="product_opts">'.$lang['available_options'].'';
foreach ($options as $value) {
$row=mysql_fetch_row($result);
$htm.='<li style="text-align:left;font-weight:normal;">'.$value.'</li>';
}
$htm.= '</ul>';
}
echo $htm;
but it returns the label as option too..
解决方案 2
其他提示
$attributes="colors:black;white;transparent;pink;";
list($attribute, $values) = array_map(
function($value) {
return array_filter(explode(';', $value));
},
explode(':', $attributes)
);
var_dump($attribute);
var_dump($values);
- Explode string by
:
. First token will be your label, second token your options. - Explode second token by
;
, and you have your options in an array.
Try
$str = "colors:black;white;transparent;pink;";
$arr = explode(";",$str);
$key = explode(":",$arr[0]);
$arr[0] = $key[1];
unset($arr[sizeof($arr)-1]);
See demo here
use split
to do like so
$options= split("[;|:]",$rows[0]);
不隶属于 StackOverflow