-1

I want to split a TSV string. The structure is:

 abc\tdef\tghi\tjklm

where \t is a tab character.

If I use preg_split to split such string $i

 $field=preg_split("/\t/", $i);

$field[3] is jklm.

However, if I have another string

abc\tdef\t\t

$field[3] is not a valid index.

How can I force empty fields into $field, such that all $field arrays would have an equal number of indexes?

Nissa
  • 215
  • 1
  • 7
  • 3
    This should be the normal behaviour. Your example gives me an array back with 4 elements where 2 and 3 are empty strings. According to doc http://php.net/manual/de/function.preg-split.php there is a flag called PREG_SPLIT_NO_EMPTY which must not be set if you want back empty elements. – user1915746 Jul 03 '17 at 10:34
  • 1
    Why even use preg split? It's not a regex problem `\t` is static so why use regex? – Andreas Jul 03 '17 at 10:55

2 Answers2

1

If your problem just for extracting Tab Separator Value data, you can use built in php function (fgetcsv()). It is more stable than use our own function. Please try this

if (($handle = fopen("test.csv", "r")) !== FALSE) {
    // extract csv using tab delimiter
    while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
        print_r($data);
    }
    fclose($handle);
}
Dolly Aswin
  • 2,684
  • 1
  • 20
  • 23
0

Like this?

$str ="abc\tdef\t\t";

Var_dump(explode("\t", $str));

https://3v4l.org/7qOPJ

Andreas
  • 23,610
  • 6
  • 30
  • 62