Jump to content

Archived

This topic is now archived and is closed to further replies.

btherl

Performance problem

Recommended Posts

I have written a function which acts like explode(), but honours quotes around elements. Here it is:

[code]##############################################################################
# The PHP explode() function, but honouring and stripping double quotes.
# Also recognizes backslash escaped double quotes.
# '"hello, there",fred' => array("hello, there", "fred")
function explode_quote($sep, $instr) {
  $out = array();
  $i = 0;
  $inquotes = false;
  $cur = "";

  while (($c = $instr{$i}) != "") {
    if ($c == '"') {
      $inquotes = !$inquotes;
    } elseif ($c == $sep) {
      if ($inquotes) {
        $cur .= $c;
      } else {
        $out[] = $cur;
        $cur = "";
      }
    } elseif ($c == '\\') { /* Single backslash */
      $i++;
      $cur .= $instr{$i};
    } else {
      $cur .= $c;
    }
    $i++;
  }

  $out[] = $cur;

  return $out;
}[/code]

However, it is not very fast. Is there a way I can write this which will make it faster?

Share this post


Link to post
Share on other sites
using regular expressions, you could probably do it in just one line. have a look at preg_split: [a href=\"http://uk2.php.net/preg_split\" target=\"_blank\"]http://uk2.php.net/preg_split[/a]

cheers
Mark

Share this post


Link to post
Share on other sites
I don't think preg_split() is useful. I need to split on commas, but commas can also be present within the fields, enclosed by quotes, for example:

[code]"first, second",third[/code]

This is two comma seperated values:

[code]first,second
third[/code]

I can't think of any regexp that will do that for me!

Also, it needs to handle backslash-escaped double quotes within values.

Share this post


Link to post
Share on other sites
If you use stripslashes() on the string before you start, you won't have to worry about escaped characters. Then your problem is reduced to one problem.

One solution you might want to look at:

[code]<?php
function explode_quote($sep, $instr) {
    $str = trim(stripslashes($instr));
    $tmpfname = tempnam("/tmp", "FOO");
    $fp = f open($tmpfname, "w");
    f write($fp, $str . "\n");
    f close($fp);
    $csvfp = f open($tmpfname,'r');
    $data = f getcsv($csvfp,strlen($str)+10,$sep);
    f close($csvfp);
    unlink($tmpfname);
    return($data);
}?>[/code]

The key to this is to use the [a href=\"http://www.php.net/fgetcsv\" target=\"_blank\"]fgetcsv()[/a] function. I don't know if the overhead of creating a temporary file is better than looping through the string character by character.

Note: remove the space between the "f" and the rest of the filesystem functions.

Ken

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.