Reputation: 517
$transData = fgets($fp);
while (!feof ($fp))
{
$transArry = explode(" ", $transData);
$first = $transArry[0];
$last = $transArry[1];
$Sub = $transArry[2];
$Grade= $transArry[3];
echo "<table width='400' ><colgroup span='1' width='35%' /><colgroup span='2' width='20%' /> <tr><td> ".$first." ".$last." </td><td> ".$Sub." </td><td> ".$Grade." </td></tr></table>";
$transData = fgets($fp);
}
My teacher wants me to change this use of explode()
to str_split()
while keeping the same output. How do I do this?
Upvotes: 4
Views: 10036
Reputation: 48031
Since you are processing a multiline file containing delimited strings, this task is a good opportunity to explore dedicated native file parsing functions.
You can parse lines with fscanf()
then print them with vprintf()
. Demo
echo '<table width="400" border="1">';
while ($transArry = fscanf($fp, "%s%s%s%s")) {
vprintf(
"\n\t<tr><td>%s %s</td><td>%s</td><td>%s</td></tr>",
$transArry
);
}
fclose($fp);
echo "\n</table>";
Or change the default delimiter of fgetcsv()
. Demo
echo '<table width="400" border="1">';
while (($transArry = fgetcsv($fp, 1000, ' ', escape: ' ')) !== false) {
vprintf(
"\n\t<tr><td>%s %s</td><td>%s</td><td>%s</td></tr>",
$transArry
);
}
fclose($fp);
echo "\n</table>";
For the sake of programming language exploration, you could also avoid parsing each line to an array then back to a string by using regex to inject the desired HTML. Demo
echo '<table width="400" border="1">';
echo preg_replace(
'#^(\S*) (\S*) (\S*) (\S*)$#m',
"\n\t<tr><td>\$1 \$2</td><td>\$3</td><td>\$4</td></tr>",
file_get_contents($filename)
);
echo "\n</table>";
Upvotes: 0
Reputation: 11575
The difference between the two explode() and str_split() is that explode uses a character to split on and the the str_split requires the number of characters. So unless the fields in the record data $transData are exactly the same length, this will require additional code. If all fields/records are of the same length, you can just drop in the function. So if each field in the record is 10 characters long, you can do:
$transArry = str_split($transData, 10);
Upvotes: 2
Reputation: 2725
If you use str_spilt you can't use the delimiter. str_split splits the string character by character and stored into each array index.And also using str_split() we can specify the limit of the string to store in array index. If you use split() function only, you can get the same output, what explode() did.
Instead of explode use the following line.
$transArry = split(" ",$transData);
Upvotes: 3