How to count the number of instances of a particular subsequence - php

I have a file that has long string; what i could not do is search and count
a particular subsequence. I want to count the number of "ABD" substring in veryLongWord.txt file. The below is what i have currently.
<?php
$file = fopen("veryLongWord.txt", "r");
/*
inside veryLongWord.txt
ABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABD
ABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABDABDBBAABAADBBADABDADDAABBABD
*/
$word = "";
while(!feof($file)) {
$line = fgets($file);
$word .= trim($line);
}
fclose($file);
$subseq = null;
$count = 0;
print $subseq . " shows " . $count . " times <br/>";
?>

There's already a function to do that: substr_count
$contentsOfVeryLongWord = file_get_contents("veryLongWord.txt");
$count = substr_count($contentsOfVeryLongWord, 'ABD');

Related

PHP, inserting CSV from external source into MySQL DB

I know this has been asked before -- I tried to read previous Q&A on the topic but I'm still stuck. Probably I read too many Q&A and have a bad mix of techniques as a result.
I don't get an error, I just don't get anything in my table. The echo $i is to help debug and I only ever get a 0 rather than expected 0 1 2 3 ... N rows.
My DB connection credentials are all fine I use them all over my site for Select statements.
$csv_file = str_getcsv("https://ds.data.jma.go.jp/tcc/tcc/products/gwp/temp/list/csv/year_wld.csv");
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile))
{
echo $i;
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$yrr = $csv_array[0];
$vals= $csv_array[1];
$sql1 = "INSERT INTO Table1(Year,Value) VALUES(" . $yrr . "," . $vals. ")";
$conn->query($sql1);
$i++;
}
The main problem here is the fact that you are trying to open a text variable as a file:
$csvfile = fopen($csv_file, 'r');
In fact you already have an array from from str_getcsv so your whole code should look like (if you can read the whole file at once):
$csvFile = array_map('str_getcsv', file("https://ds.data.jma.go.jp/tcc/tcc/products/gwp/temp/list/csv/year_wld.csv"));
array_shift($csvFile); //we remove the headers
$i = 0;
/**
* Removes all the "*" and "+" symbols as I assume that you want a float since you are not wrapping it in the sql query
*/
function removeUnwantedChars($string) {
return preg_replace('/[^0-9\\.\\-]/i', '', $string);
}
foreach($csvFile as $csvData) {
echo $i++;
$yrr = $csvData[0];
$vals = removeUnwantedChars($csvData[1]);
$sql1 = "INSERT INTO Table1(Year,Value) VALUES(" . $yrr . "," . $vals. ")";
$conn->query($sql1);
}
If you cannot read it all at once then I suggest to first download the file line by line:
<?php
$url = "https://ds.data.jma.go.jp/tcc/tcc/products/gwp/temp/list/csv/year_wld.csv";
$fileHandle = fopen($url, "r");
/**
* Removes all the "*" and "+" symbols
*/
function removeUnwantedChars($string) {
return preg_replace('/[^0-9\\.\\-]/i', '', $string);
}
$i = 0;
$headersSkipped = false;
while ($csvData = fgetcsv($fileHandle)) {
if (!$headersSkipped) {
$headersSkipped = true;
continue;
}
echo $i++;
$yrr = $csvData[0];
$vals = removeUnwantedChars($csvData[1]);
$sql1 = "INSERT INTO Table1(Year,Value) VALUES(" . $yrr . "," . $vals. ")";
$conn->query($sql1);
}
fclose($fileHandle);
Yet like said by #Shadow above it is always great to be more verbose. So in case query returned false then it would be great to output the last error (if you are using PDO then errorInfo() function.

Adding a string to the end of each line but not the first line

I am trying to add a string to the end of eachline. So far this works. However I dont want the string to be added to the end of the first line. How can I do this?
So far i have got:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
while(!feof($baseFile)) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
I have also tried to loop it by doing this:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
$x = 0;
while(!feof($baseFile)) {
if ($x > 0) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
$x++;
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
So the end result would look like:
firstonestring
secondonestring
thirdonestring
and so on.
I hope you can help me!
Ben :)
Just add a counter to your loop:
$counter = 0;
while(!feof($baseFile)) {
$line = fgets($baseFile)
if($counter++ > 0){
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}else{
$newFile.= $line . "\n";
}
}
Also, you seem to be writting the new file, only to reopen it and append more data. There is no need to do that, just append to the contents before you write it the 1st time:
fclose($baseFile);
file_put_contents("newfile.txt", $newFile . $EOLString);
//$bingName = "newfile.txt";
//$bingFile = fopen($bingName, "a+");
//fwrite($bingFile,$EOLString);
//fclose($bingFile);
Alternativly, you can just read in the whole file, split into lines, and rejoin:
$EOLString="string \n";
$lines = explode("\n", file_get_contents("file.txt"));
$first = array_shift($lines);
file_put_contents("newfile.txt", $first . "\n" . implode($EOLString, $lines) . $EOLString);
//done!
By using a flag
$first = TRUE;//set true first time
while (!feof($baseFile)) {
$line = fgets($baseFile);
if (!$first) {// only enter for false
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}
$first = FALSE;// set false except first
}

PHP: Insert line break after every $num word in a text file

I want to clean up a .txt file to make it more readable by inserting a line break after every 4th word. The file has been filled with data from an array.
This is what I've come up with so far by looking at this and this:
<?php
require "simple_html_dom.php";
$html = file_get_html("http://www.lipsum.com/");
$data = array();
$counter = 0;
foreach($html->find("div") as $tr){
$row = array();
foreach($tr->find("div") as $td){
$row[] = $td->plaintext;
}
$data[] = $row;
}
ob_start();
var_dump($data);
$data = preg_replace('~((\w+\s){4})~', '$1' . "\n", $data);
file_put_contents('new_text_file.txt', $data);
//$handlefile = fopen("newfile.txt", "w") or die("Unable to open file!");
//file_put_contents('newfile.txt', $data);
//$output = ob_get_clean();
//$outputFile = "newfile.txt";
//fwrite($handlefile, $output);
//fclose($handlefile);
?>
As you can see I've created a for loop and two if statements to "count" the spacing between the words, and when the counter variable has reached 3, a line break is inserted. But it doesn't work since no data from the website is printed to the text file in the first place. It works however, if I remove the for loop and the if statements, without the sorting of course.
Any type of help is appriciated!
Edit: updated code.
Edit 2: final working version. Original question left for further reference.
This is the final working version:
<?php
require "simple_html_dom.php";
$html = file_get_html("http://www.lipsum.com/");
$data = array();
$counter = 0;
foreach($html->find("div") as $tr){
$row = array();
foreach($tr->find("div") as $td){
$row[] = $td->plaintext;
}
$data[] = $row;
}
ob_start();
var_dump($data);
$handlefile = fopen("newfile.txt", "w") or die("Unable to open file!");
file_put_contents('newfile.txt', $data);
$output = ob_get_clean();
$outputFile = "newfile.txt";
fwrite($handlefile, $output);
fclose($handlefile);
function MakeFileReadable($source , $export) {
$content = file_get_contents($source);
$x = explode (" " , $content);
$newx = "";
$count = 1;
foreach ($x as $word) {
$newx .= $word . " ";
if ($count %12 ==0) $newx .= "\r\n";
$count ++;
}
$fp = fopen("file-export.txt" , 'w');
if (!$fp) die("There is a problem with opening file...");
fwrite($fp , $newx);
fclose($fp);
}
MakeFileReadable("newfile.txt" , "file-export.txt");
?>
Use some array functions
$string = "one two three four five six seven eight nine ten eleven tweleve thirteen fourteen";
$arr = explode (" " , $string);
$lines = array_chunk($arr,4);
foreach($lines as $line)
echo implode (" ", $line)."\r\n";
result
one two three four
five six seven eight
nine ten eleven tweleve
thirteen fourteen
Here's a regex solution.
<?php
$test = 'one two three four five six seven eight nine ten eleven tweleve thirteen fourteen';
echo preg_replace('~((\w+\s){4})~', '$1' . "\n", $test);
Output:
one two three four
five six seven eight
nine ten eleven tweleve
\w is a word character (Alphanumeric characters plus "_", http://en.wikipedia.org/wiki/Regular_expression), if you only want A-Z use [a-z] and use the i modifier to make it case insensitive, ~((\w+\s){4})~i. The \s is a whitespace and the {4} is requiring 4 occurrences of the \w+\s.
Per your code...
$data = preg_replace('~((\w+\s){4})~', '$1' . "\n", $data);
file_put_contents('new_text_file.txt', $data);
http://php.net/manual/en/function.file-put-contents.php
Per updated code:
<?php
require "simple_html_dom.php";
$html = file_get_html("http://www.lipsum.com/");
$data = array();
$counter = 0;
foreach($html->find("div") as $tr){
$row = array();
foreach($tr->find("div") as $td){
$row[] = $td->plaintext;
}
$data[] = $row;
}
$data = preg_replace('~((\w+\s){4})~', '$1' . "\n", implode(' ', $data));
file_put_contents('new_text_file.txt', $data, FILE_APPEND | LOCK_EX);
Finally tested code:
<?php
function MakeFileReadable($source , $export) {
$content = file_get_contents($source);
$x = explode (" " , $content);
sort($x);
$newx = "";
$count = 1;
foreach ($x as $word) {
$newx .= $word . " ";
if ($count %4 ==0) $newx .= "\r\n";
$count ++;
}
$fp = fopen($export , 'w');
if (!$fp) die("There is a problem with opening file...");
fwrite($fp , $newx);
fclose($fp);
}
MakeFileReadable("file-input.txt" , "file-export.txt");

Read line for first top 10 lines and display word in each line of 10 lines using PHP

I have the PHP code as below:
<?php
$path = "files/stats_pmta.affinitead.net.2012-12-12.txt";
$num = 10;
$fh = #fopen($path, 'r');
if ($fh){
for ($i=0;$i<$num;$i++){
$newfile = fgets($fh,1024);
$t = explode(";", $newfile);
echo $t;
echo "<br>";
}
} else {
echo 1;
}
?>
I want to read all data in file stats_pmta.affinitead.net.2012-12-12.txt that read only first 10 lines of the file below:
2012-12-12-0551;affinitead.net;1221588;106346;8.70;gmail.com;123577;7780;6.29
2012-12-12-0551;affinitead.net;1221588;106346;8.70;wanadoo.fr;123562;9227;7.46
2012-12-12-0551;affinitead.net;1221588;106346;8.70;yahoo.fr;104819;1685;1.60
2012-12-12-0551;affinitead.net;1221588;106346;8.70;orange.fr;87132;7341;8.42
2012-12-12-0551;affinitead.net;1221588;106346;8.70;laposte.net;79597;1040;1.30
2012-12-12-0551;affinitead.net;1221588;106346;8.70;hotmail.fr;77601;14107;18.17
2012-12-12-0551;affinitead.net;1221588;106346;8.70;neuf.fr;67392;1793;2.66
2012-12-12-0551;affinitead.net;1221588;106346;8.70;hotmail.com;55300;10494;18.97
2012-12-12-0551;affinitead.net;1221588;106346;8.70;free.fr;43422;1706;3.92
2012-12-12-0551;affinitead.net;1221588;106346;8.70;sfr.fr;39063;251;.64
2012-12-12-0551;affinitead.net;1221588;106346;8.70;aol.com;32061;9859;30.75
2012-12-12-0551;affinitead.net;1221588;106346;8.70;club-internet.fr;22424;233;1.03
2012-12-12-0551;affinitead.net;1221588;106346;8.70;yahoo.com;18646;1365;7.32
2012-12-12-0551;affinitead.net;1221588;106346;8.70;voila.fr;18513;3650
After I read first top 10 lines I want to display the word in each line like:
2012-12-12-0551;affinitead.net;1221588;106346;8.70;gmail.com;123577;7780;6.29
I want to display gmail.com 123577 7780 6.29
But PHP code above I just got the output array.I don't know how to fix this.Anyone help me please , Thanks.
You could do something like this:
$path = 'path/to/file'
$fp = fopen($path, 'r');
$count = 0;
while($columns = fgetcsv($fp, 256, ';', '"')
{
if(++$count > 10)
break;
echo implode("\t", $colums);
}
If you don't know, how implode works, look here: http://de1.php.net/manual/de/function.implode.php
This is a way you could do it by using the PHP-function explode.
$textFile = file_get_contents("test.txt");
$lineFromText = explode("\n", $textFile);
$row = 0;
foreach($lineFromText as $line)
{
if($row <= 10)
{
$words = explode(";",$line);
echo $words[5] . ' ' . $words[6] . ' ' . $words[7] . ' ' . $words[8];
$row++;
}
}
Edited the code so that you can replace your own, you might want to check if the file is empty e t c before trying to do anyting thou.

PHP: Splitting a string and printing

I have server output that looks like this
PLAYER_ENTERED name ipaddress username
If the string contains PLAYER_ENTERED there will always be 3 spaces within the string separating it (how can this be modified so it does this too?). I would like to print out only the ipaddress and username (last 2 sections).
How can this be done?
This is code that prints out the whole thing:
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
if (strstr($line, $q))
{
print "<li>$line";
}
I imagine this using explode() but I've given up trying since I hardily know how to code php.
Desired Output
username ipaddress
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
if (strstr($line, $q))
{
$data = explode(" ", $line); // split using the space into an array
// array index 0 = PLAYER_ENTERED
print "IP:" . $data[1]; // array index 1 = IP
print "Name: " . $data[2]; // array index 2 = name
}
}
You can use substr()to check if the first 14 characters of $line equals PLAYER_ENTERED and then you use list() and explode() to extract the data from the line.
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while(($line = fgets($f)) !== FALSE)
{
if(substr($line, 0, 14) == 'PLAYER_ENTERED'){
list($event, $name, $ip, $username) = explode($string); // here they come!
echo 'Name: ' . $name . ', ip: ' . $ip . ', username: ' . $username;
}
}
try this ...
<?
$str = "PLAYER_ENTERED name 108.21.131.56 username";
if ( preg_match( "~^(.+)\s+(.+)\s+([\d\.]+)\s+(.+)$~msi", $str, $vv ))
echo $vv[3] . " and " .$vv[4] ;
else "N/A";
?>
IMHO Perl regexp - is the right Way to parse strings ...
One way would be:
$tokens = explode(' ', $line);
if (count($tokens) == 4 && $tokens[2] == $q) {
printf('IP: %s Username: %s', $tokens[2], $tokens[3]);
}
<?php
$str = 'PLAYER_ENTERED name 108.21.131.56 username';
$data = explode(" ", $str )
print_r($data)
?>

Categories