Explode takes a parameter to stop exploding after a set number of splits
Explode has a limit parameter. Happy day at Agaric!
This code below was written offline when I was merely hoping that explode could be limited to splitting on its first parameter only the first time said parameter is seen:
<?php
function taxonomy_xml_obo_add_pair(&$line, &$term) {
$parts = explode(': ', $line);
if (count($parts) == 2) {
$key = $parts[0];
$value = $parts[1];
if (taxonomy_xml_obo_defines_multiple($key)) {
if (!isset($term[$key])) {
$term[$key] = array();
}
$term[$key][] = $value;
} else {
$term[$key] = $value;
}
// drupal_set_message('adding line: ' . $parts[0] . ': ' . $parts[1]);
}
elseif (count($parts) > 2) {
drupal_set_message('too many parts we will have to implode here if there is no way to tell explode to stop at one');
drupal_set_message('<pre>'.var_export($parts,TRUE).'</pre>');
}
elseif (count($parts) == 1 && $parts[0]) {
drupal_set_message(t("Non-parsed line: %s", $parts[0]));
}
}
?>
Here's the code happily and much more cleanly rewritten to use explode's wonderful third parameter: the number of parts that can be made. After that, the remainder is returned as the final part without wasting any more effort in processing.
<?php
function taxonomy_xml_obo_add_pair(&$line, &$term) {
$parts = explode(': ', $line, 2);
if (count($parts) == 2) {
$key = $parts[0];
$value = $parts[1];
if (taxonomy_xml_obo_defines_multiple($key)) {
if (!isset($term[$key])) {
$term[$key] = array();
}
$term[$key][] = $value;
} else {
$term[$key] = $value;
}
}
elseif (count($parts) == 1 && $parts[0]) {
drupal_set_message(t("Non-parsed line: <tt>%s</tt>", $parts[0]), 'warning');
}
}
?>
Comments
Post new comment