• preg_split -
This Perl-style function is equivalent to the split() function previously discussed with the
exception of allowing Perl-style regular expressions. The third optional component of the
preg_split() function can be entered to limit the number of changes that take place. Failing to enter a
numeric limit (or a -1), ensures that there is no limit on the changes that can take place.
<?php
$csv_text = "5, \"Amsterdam\", \"NLD\", \"Noord-Holland\",
731200";
$csv_array = preg_split("/\,/",$csv_text);
foreach ($csv_array as $csv_column) {
print "$csv_column<br>";
}
?>
The script above creates an array called $csv_row that contains the following element: [0] = 5,
[1]="Amsterdam", [2]="NLD", [3]="Noord-Holland", [4]=731200). The foreach iterative control
statement prints each of these elements on the screen on their own lines. A third component can be
placed in the split function that would limit the number of array elements that would be created. By
adding 3 to the split function in the above script (preg_split("/\,/",$csv_text, 3) the
array elements that would be created would consist of: [0]=5, [1]="Amsterdam", [2]="NLD", "Noord-
Holland", 731200.
Comments
Post a Comment