Forum Moderators: coopster

Message Too Old, No Replies

How to detect file delimiter?

         

smagdy

12:26 pm on Nov 18, 2007 (gmt 0)

10+ Year Member



Hello!

I will be reading file contents dynamically which could be comma or tab delimited...

so first I will read them in array like this:
$data_rows = file($file);

then I want to explode over the delimiter after I detect it?

So is there a simple way to detect it?

Thanks in advance

ayushchd

12:53 pm on Nov 18, 2007 (gmt 0)

10+ Year Member



Why don't you use strpos function and detect the presence of a comma, if the comma is present, explode through comma else explode the other way round?
Does it help?

Just see if this helps...
$comma = strpos($data_rows, ",");
if ($comma === true)
{
$data = explode(",", $data_rows);
}
else
{
//explode tabbed content
}

smagdy

1:00 pm on Nov 18, 2007 (gmt 0)

10+ Year Member



But what if it is tabbed but the string contains also a comma?

Habtom

1:10 pm on Nov 18, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



But what if it is tabbed but the string contains also a comma?

You might count the occurrences and see which one is really delimiting. But I don't see a way to surely tell what the delimiter is. For the following text, for example, you wouldn't know what the delimiter is just by looking at it.

this,text,is;second,part;and;third,part

I don't believe there is anything you can do, to surely tell what kind of delimiter a certain file contains.

smagdy

1:18 pm on Nov 18, 2007 (gmt 0)

10+ Year Member



But when we save a file and choose the type of the delimiter, doesnt this have a flag or something in the structure of the file that we can detect or no?

Thanks to all

PHP_Chimp

7:32 pm on Nov 18, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you let people choose then you could put that choice in at the beginning of the file, or in the file name...there are bound to be other methods as well.

name -
example_file.tab.php
example_file.comma.php

$dot = strpos($file_name, '.');
$type = substr($file_name, $dot+1, strlen($file_name)-4);

beginning of file -

type = tabbed ¦ comma
// rest of file contents start here

$find = preg_match('%^type =?(tabbed¦comma)%$', $file, $match);
$type = $match[1]; // this should be the parenthesised bit

At least those 2 versions may give you a better idea of how to find the type. Then you will know what delimiter you are looking for.