User login

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');
  }
}
?>

Resolution

Searched words: 
split string slice string into parts cut data into chunks with php regexp divide on key only for first occurrence split into multiple values on separator but only for so many times then return the rest

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.