PHP Split string with exception - php

I have a string that need to be split out :
3,1,'2015,05,14,11,18,0', 99
I want to split it into
3
1
'2015,05,14,11,18,0'
99
How could I do this with PHP ?

One of the comments (#tuananh in particular) said csv parser, so a little bit of trial, fgetcsv will work too, you'll just got to have that temporary file that holds the simple string, just unlink it after the operation.
Just set the enclosure to single quotes so that when the parser breaks it up, it gets the whole string enclosed with single quotes.
$string = "3,1,'2015,05,14,11,18,0', 99";
file_put_contents('temp.csv', $string); // create temporary file
$fh = fopen('temp.csv', 'r'); // open
$line = fgetcsv($fh, strlen($string) + 1, ',', "'"); // set enclosure to single quotes
fclose($fh);
unlink('temp.csv'); // remove temp file
print_r($line); // Array ( [0] => 3 [1] => 1 [2] => 2015,05,14,11,18,0 [3] => 99 )
// echo implode("\n", $line);
Sidenote: If this is indeed a csv file, then just use fgetcsv for the whole thing.
EDIT: As #deceze said about use the csv function for strings
There's this thing called str_getcsv, so no need to actually put it inside a file the unlink it whatsoever.
$string = "3,1,'2015,05,14,11,18,0', 99";
$line = str_getcsv($string, ',', "'"); // set enclosure to single quotes
print_r($line);

Related

Get the count of unique words from all .txt files in a directory

I have a directory of text files. I want to loop through each of the text files in the directory and get the overall count of unique words (count of vocabulary), not for each individual file, but for ALL the files together. In other words, I want the number of unique words within all the files together, and NOT the number of unique words for each individual file.
For example, I have three text files in a directory. Here are their contents:
file1.txt -> here is some text.
file2.txt -> here is more text.
file3.txt -> even more text.
So the count of unique words for this directory of text files in this case is 6.
I have tried to use this code:
$files = glob("C:\\wamp\\dir");
$out = fopen("mergedFiles.txt", "w");
foreach($files as $file){
$in = fopen($file, "r");
while ($line = fread($in)){
fwrite($out, $line);
}
fclose($in);
}
fclose($out);
to merge all the text files and then after using this code I planned to use the array_unique() on mergedFiles.txt. However, the code is not working.
How can I get the unique word count of all the text files in the directory in the best way possible?
You can try this :
$allWords = array();
foreach (glob("*.txt") as $filename) // loop on each file
{
$contents = file_get_contents($filename); // Get file contents
$words = explode(' ', $contents); // Make an array with words
if ( $words )
$allWords = array_merge($allWords, $words); // combine global words array and file words array
}
var_dump(count(array_unique($allWords)));
EDIT Other version which :
remove dots
remove multiple spaces
match word if missing space between end of sentence and new one.
function removeDot($string) {
return rtrim($string, '.');
}
$words = explode(' ', preg_replace('#\.([a-zA-Z])#', '. $1', preg_replace('/\s+/', ' ',$contents)));
$words = array_map("removeDot", $words);
Unless you have legitimate reasons not to simply concatenate the files and process their content as a concatenated string, use this snippet to target txt files in a directory, join their texts, make the text lowercase, isolate words, remove duplicates, then count unique words:
Code (not fully tested on a filesystem): (Demo)
echo count(
array_unique(
str_word_count(
strtolower(
implode(
' ',
array_map(
'file_get_contents',
glob("*.txt")
)
)
),
1
)
)
);
Assuming texts from file:
[
'here is some text.',
'here is more text.',
'even more text.'
]
The output is 6 from a unique array of:
array (
0 => 'here',
1 => 'is',
2 => 'some',
3 => 'text',
6 => 'more',
8 => 'even',
)
Modify the snippet as needed: perhaps use a different technique/algorithm to identify "words", or use mb_strtolower(), or don't use strtolower() at all.

Get contents from a text file and save its values

I need to get the contents of a text file called file.txt. The contents of that file are:
word1,word 2,word 3 1,another word 1,
I have a config.php which includes:
$file = "file.txt";
$value = explode(",", $file);
And script.php file which will execute other commands based on $value which includes:
if (count(explode($value, $chat))>1) {
After that, it will execute a command if the $value was detected in $chat. So, I need the $value to be a separate word in file.txt.
How can I do this?
If you're looking for more flexibility, you might want to try using preg_split rather than explode, which splits on a regular expression. For example, to split on newlines and commas, you could use this:
$text = file_get_contents('text.txt');
$values = preg_split('/[\n,]+/', $text);
Testing it out:
$s = "word1,word 2\n word 3";
print_r(preg_split('/[\n,]+/', $s));
Output:
Array
(
[0] => word1
[1] => word 2
[2] => word 3
)
Putting that into your script:
$file = "file.txt";
$text = file_get_contents($file);
$values = preg_split('/[\n,]+/', $text);
Then $values is an array, which you can loop over in the other script:
foreach ($values as $value) {
// do whatever you want with each value
echo $value;
}
Reading file contents:
file_get_contents
Explode string:
explode
Get file as array (each line => one item):
file
BTW: a short google would already answer your question...
In config.php add this code, be sure that the file is in the same folder
$value = file_get_contents('file.txt');
Then in script.php add this code:
$pieces = explode(",", $value);
Read more about file_get_contents and explode. (Click on the names)

php - eliminate the space in the beginning while writing to CSV file

I am writing array values to a CSV file using PHP. In the array values, I have included a line break using \n. After the array values are updated, I am using the implode function as below.
$newLine[] = $row[$i].",";
$newLine[] = "\n";
$csv2 [] = implode(" ", $newLine);
However, while writing to the CSV file, an extra space gets appended to the front of the line. This is causing me some problems in display. I want to eliminate the space in front of the line while it is getting written. I tried to do the below.
$line1 = str_replace(' .','.',$line);
However, I am not able to write without the space in beginning to the CSV file.
You don't need to use spaces at all:
$newLine[] = $row[$i].",";
$csv2 [] = implode("\n", $newLine);
$csv2[] = trim ( implode("\n", $newLine) , "\n");
This should work since it removes only line breaks at the beginning and end of the string.

Wrap CSV values generated by PHP fputcsv() with " "

So, my code generates a CSV file using PHP's built-in fputcsv function.
For the delimiter, I use ',' (a comma).
For the enclosure, I use '"' (a double-quote).
However, when I try something like
fputcsv($file,array('a','b',"long string, with commas",NULL,''),',','"');
it outputs
a,b,"long string, with commas",,
but I would like it to output
"a","b","long string, with commas","",""
Is there an easy way to deal with this, or would I have to write a replacement for fputcsv?
This is not usually a problem for CSV files.
fputcsv puts quotes around the value if it would be ambiguous. For example,
a,b,"long string, with commas",,
is not ambiguous, but,
a,b,long string, with commas,,
is, and will in most (read: all) cases be interpreted by the CSV reader as having more than 5 fields.
CSV parsers will accept string literals even without quotes around them.
If you want quotes around the values anyway, the following snippet would do that. It doesn't escape quotes inside the string - that exercise is left to the reader:
$row = '"' . implode('", "', $rowitems) . '"';
You would want to put this in a loop for all your rows.
I worked around this by inserting some bogus string characters, with a space, ## ##, and then removing them. Here's a sample implementation:
//$exported is our array of data to export
$filename = 'myfile.csv';
$fp = fopen($filename, 'w');
foreach ($exported as $line => $row) {
if ($line > 0) {
foreach ($row as $key => $value) {
$row[$key] = $value."## ##";
}
}
fputcsv($fp, $row);
}
fclose($fp);
$contents = file_get_contents($filename);
$contents = str_replace("## ##", "", $contents);
file_put_contents($filename, $contents);
This encloses all fields in double quotes, including empty ones
I think solution will be like this,
$order_header_arr = array("Item1", "Item2","This is Item3");
fputcsv($fp, $order_header_arr,',',' ');
remember " "[Space] Between third parameter of fputcsv
Any reason you can't str_replace(',,',',"",',$output); ? You'd also have to see if the last or first character is a comma and if so, replace the comma with ,""
fputcsv will not enclose all array variables in quotes. Having a numeric array value without quotes may be correct but presents a problem when a label or address program encounters a numeric defined US zip code because it will strip the leading zeros when printing. Thus 05123-0019 becomes 5123-19.
To enclose all values, whether they exist or not, in quotes I read the input file with fgetsrc and write a corrected version using fwrite. fgetsrc reads the record into array variables. Since fwrite writes a variable, you must string the array variables, enclose them in quotes and separate the array variable with a comma. Then add the record separator.
<?php
// fgetcsv - read array with fgetcsv and string into output variable
// then write with fwrite
// $ar is the array populated from fgetcsv and $arc is the variable strung
// with array variables enclosed in quotes and written using fwrite.
$file_in = fopen("reinOCp.csv","r") or die("Unable to open input file
reinOCp.csv!");
$file_out = fopen("printLABEL.csv", "w") or die("Unable to open output file
prtLABEL!");
while (!feof($file_in)) { //loop through each record of the input file
$ar=fgetcsv($file_in); //read the record into array $ar
if (is_array($ar)){ //this loop will string all the array values plus
// the end of record into variable $arc and then write the variable
$arc = ""; //clear variable $arc
foreach ($ar as $value) {
$arc .= '"' . $value . '",'; // add the array values, enclose in
// quotes with comma separator and store in variable $arc
}
$arc .= "\n"; //add end of record to variable $arc
fwrite($file_out, $arc) or die ("ERROR: Cannot write the file");
//write the record using variable $arc
}
}
echo "end of job";
fclose($file_in);
fclose($file_out);
?>

Explode function in PHP

I have the following notepad file;
dbName:
tableName:
numberOfFields:
I am trying to write a php app which assigns the value of dbName to $dbName, tableName to $tableName and numberOfFields to $numFields.
My code is:
$handle = #fopen("config.txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
list($dbName, $tableName, $numFields) = explode(":", "$buffer");
}
fclose($handle);
}
however, ":" doesn't work as there are line breaks in between dbName and table Name. How do I explode $buffer, keeping the line breaks in the notepad file?
Thank you.
Have a look at the file function. It takes care of opening and reading the file, and returns an array of lines from the file. You could then iterate through the array and operate on each line individually.
http://us.php.net/manual/en/function.file.php
you can do this:
$data=file_get_contents("file");
$s = preg_split("/\n\n+/m", $data);
print_r($s);
You can use the chr($INT); function to look for the line break in your explode call.
Your can find more on the chr function here:
http://php.net/manual/en/function.chr.php
Add you can find the ascii chars for line break at:
http://www.asciitable.com/
fgets returns only one line. There is no way $buffer would ever have all three items at once, so that assignment to list() is wrong. For the first line, explode() will return an array with two items: "dbName" (text before the colon) and "" (text after the colon).
Does this work:
list ($dbName, $tableName, $numFields) = explode (':', implode ('', file ('config.txt')));
If you're sure of the line contents, and the file will not grow arbitrarily large:
1 <?php
2
3 $handle = #fopen("config.txt", "r");
4 if ($handle) {
5 $buffer = "";
6 while (!feof($handle)) {
7 $buffer = $buffer . trim(fgets($handle, 4096));
8 }
9 fclose($handle);
10
11 list($dbName, $tableName, $numFields) = explode(":", $buffer);
12 }
13
14 ?>
The while loop will go through all the lines and concatenate onto the same buffer after removing whitespace. This leaves just the content separated by ":". This is now amenable to explode.
As Nicolas wrote, feof gets one line at a time, so the list assignment needs to happen outside the loop.

Categories