I have a file named test.txt and i want to remove the lines from this file which have length of less than 30 characters and line starting with Capital letter word and ending with an dot or question mark should not be deleted.
For example content of test.txt file is:
text 1
text 2
text 3
Long text.
text 4
Long text 2?
After filtering, result should be
Long text.
Long text 2?
<?php
# create and load the HTML
include('simple_html_dom.php');
$tekst = file_get_html('http://www.naszawiedza.pl/')->plaintext;
foreach ($tekst as $key=>&$value) {
if (strlen($value) > 60) {
unset($yourArray[$key]);
}
}
echo $tekst;
//kropka
$string = $tekst;
$substr = '.';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
//znak zapytania
$string = $tekst;
$substr = '?';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
//podwójna spacja
$string = $tekst;
$substr = '\r\n\r\n';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
//Wykrzyknik
$string = $tekst;
$substr = '!';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
//tabulator
$string = $tekst;
$substr = ' ';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
echo $newstring;
// zmienna $dane, która będzie zapisana
// może także pochodzić z formularza np. $dane = $_POST['dane'];
$dane = $newstring;
// przypisanie zmniennej $file nazwy pliku
$file = "testy.txt";
// uchwyt pliku, otwarcie do dopisania
$fp = fopen($file, "a");
// blokada pliku do zapisu
flock($fp, 2);
// zapisanie danych do pliku
fwrite($fp, $dane);
// odblokowanie pliku
flock($fp, 3);
// zamknięcie pliku
fclose($fp);
//usun puste wiersze
$plik = "testy.txt";
// odczyt
$bufor = array();
$fd = fopen($plik, "r");
while (!feof ($fd))
{
$linia = fgets($fd, 1024);
if(strlen(trim($linia)))
{
$bufor[] = $linia;
}
}
fclose($fd);
// zapis
$fdw = fopen($plik, "w");
foreach($bufor as $wiersz)
{
fwrite($fdw, $wiersz);
}
fclose($fdw);
Here is an sample code that will do this thing
test.txt contents:
text 1
text 2
Long text.
text3
Long text 2?
Line with 30 characters ending with a question mark?
text4
<?php
$file = fopen("test.txt", "r");
$i = 0;
$string = "";
while(!feof($file))
{
// get the line
$line = trim(fgets($file));
// check if line have 30 characters
if(strlen($line) > 30)
{
// get first character ascai value
$value = ord(substr($line, 0, 1));
// get the last character
$last = substr($line, -1);
// now check if it has allowed criteria
if((($value >= 65 && $value <= 90) && ($last == '.' || $last == '?')))
{
$string .= $line."\n";
}
}
}
fclose($file);
// put the proccessed content back to file
file_put_contents("test.txt", trim($string));
?>
Ouput after executing code
Line with 30 characters ending with a question mark?
hope it will help you
Full program code. It gives me empty file. Should be here only sentences with more than 30 chars and with capital letter on beginning and question mark or dot at the end.
<?php
# create and load the HTML
include('simple_html_dom.php');
$tekst = file_get_html('http://www.naszawiedza.pl/')->plaintext;
foreach ($tekst as $key=>&$value) {
if (strlen($value) > 60) {
unset($yourArray[$key]);
}
}
echo $tekst;
//kropka
$string = $tekst;
$substr = '.';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
//znak zapytania
$string = $tekst;
$substr = '?';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
//podwójna spacja
$string = $tekst;
$substr = '\r\n\r\n';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
//Wykrzyknik
$string = $tekst;
$substr = '!';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
//tabulator
$string = $tekst;
$substr = ' ';
$attachment = "\r\n";
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
echo $newstring;
// zmienna $dane, która będzie zapisana
// może także pochodzić z formularza np. $dane = $_POST['dane'];
$dane = $newstring;
// przypisanie zmniennej $file nazwy pliku
$file = "testy.txt";
// uchwyt pliku, otwarcie do dopisania
$fp = fopen($file, "a");
// blokada pliku do zapisu
flock($fp, 2);
// zapisanie danych do pliku
fwrite($fp, $dane);
// odblokowanie pliku
flock($fp, 3);
// zamknięcie pliku
fclose($fp);
//usun puste wiersze
$plik = "testy.txt";
// odczyt
$bufor = array();
$fd = fopen($plik, "r");
while (!feof ($fd))
{
$linia = fgets($fd, 1024);
if(strlen(trim($linia)))
{
$bufor[] = $linia;
}
}
fclose($fd);
// zapis
$fdw = fopen($plik, "w");
foreach($bufor as $wiersz)
{
fwrite($fdw, $wiersz);
}
fclose($fdw);
$file = fopen("testy.txt", "r");
$i = 0;
$string = "";
while(!feof($file))
{
// get the line
$line = trim(fgets($file));
// check if line have 30 characters
if(strlen($line) > 30)
{
// get first character ascai value
$value = ord(substr($line, 0, 1));
// get the last character
$last = substr($line, -1);
// now check if it has allowed criteria
if((($value >= 65 && $value <= 90) && ($last == '.' || $last == '?')))
{
$string .= $line."\n";
}
}
}
fclose($file);
// put the proccessed content back to file
file_put_contents("testy.txt", trim($string));
?>
Related
I want to remove blank line from this text file :
test1
test2
test3
test4
So I try this code in PHP :
$file = __DIR__.$namefile;
foreach ($file as $k => $v) {
if (!trim($v))
unset($lines[$k]);
}
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
$array1[] = $nl;
}
But it does not work. Thanks for your help !
How about exploding each new line and checking if it's empty?
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array();
foreach ($lines AS $line) {
if (!empty($line)) {
$result[] = $line;
}
}
$result = implode("\n", $result);
Or, as Henders suggests, look at https://stackoverflow.com/a/7972266/1441858:
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array_filter($lines, 'trim');
$result = implode("\n", $result);
$file = __DIR__.$namefile;
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
if (trim($line) != "") {
$array1[] = $nl;
}
}
fclose($f);
$file = __DIR__.$namefile;
$lines = explode("\n", file_get_contents($file));
$result = array_filter($lines);
echo implode("\n", $result);
file_put_contents($file, implode("\n", $result)); //save
Or use:
$result = array_filter($lines, 'trim');
If there can be whitespaces in blank lines.
I am learning PHP and files and I am trying to write some code that put data in a binary file.
here's my code:
Write
<?php
echo "\n\nWRITE: \n\n";
$c = array();
$data = '';
$c['name'] = 'abcdefghijklmnopqrstuvwxyz';
$data .= implode('', $c);
$fp = fopen('test.bin', 'wb');
$len = strlen($data);
echo "\nFILE CONTENT: $data (strlen: $len)\n\n";
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data{$i}));
fwrite($fp, pack("C", $hx));
}
echo "Last char is: $hx which mean: ";
echo chr(hexdec('7a'));
echo "\n--------------------------------------------\n";
fclose($fp);
Output
FILE CONTENT: abcdefghijklmnopqrstuvwxyz (strlen: 26)
Last char is: 7a which mean: z
Read
<?php
echo "\n--------------------------------------------\n";
echo "\n\nREAD: \n\n";
$fp = fopen('test.bin', 'rb');
$fseek = fseek($fp, 0, SEEK_SET);
if($fseek == -1) {
return FALSE;
}
$data = fread($fp, 26);
$arr = unpack("C*", $data);
$return = '';
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
$n = '';
$arr = array();
$arr['name'] = substr($return, 0, 26);
print_r($arr);
echo "\n--------------------------------------------\n";
Output
Array
(
[name] => abcdefghipqrstuvwxy
)
Where are the missing letters like the z, m, n or o ?
EDIT 6-3-14 7h36 am: I would like to have the .bin file not plain text if possible
You are trying to set HEX chars in a char (C - unsigned char) instruction.
echo "\t";
foreach( array('0x41', 65, 'a') as $o )
echo $o."\t";
echo "\n";
foreach( array('c*','C*','a*','A*','h*','H*','v*','n*','S*') as $o ){
echo $o . "\t";
foreach( array(0x41, 65, "a") as $oo ) {
echo pack($o, $oo);
echo "\t";
}
echo "\n";
}
If you run this, you will see quickly how pack works with the 3 different values of a (HEX, DEC and normal).
You have to use the h instruction to accomplish what you need.
function writeToFile($data) {
$fp = fopen(FILENAME, 'wb');
$len = strlen($data);
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data[$i]));
$result = fwrite($fp, pack("h*", $hx));
if(!$result) {
// show something
}
}
fclose($fp);
}
Now, for read that data. You will need to use the same one h and split the string you get back (split it using str_split with the parameter 2 since it's HEX 00 = 0 and FF = 255 - assuming you won't go over 255). Since h returns an array with a single element. Once you get your string back, you need to convert the number you get from the ord in the writeToFile using the chr function.
function readFromFile($lenght, $pos = 0) {
$return = '';
$fp = fopen(FILENAME, 'rb');
if(!$fp) {
// show something
}
$fseek = fseek($fp, $pos, SEEK_SET);
if($fseek == -1) {
// show something
}
$data = fread($fp, $lenght);
$data = unpack("h*", $data);
$arr = str_split(current($data), 2);
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
return $return;
}
Now, you create your string and write to the file:
$data = 'This should work properly, thanks for StackOverFlow!';
$len = strlen($data);
writeToFile($data);
Then read back:
echo readFromFile($len);
The content of your file will look like this:
E<86><96>7^B7<86>öWÆF^Bwö'¶^B^G'ö^GV'Æ<97>Â^BG<86>^Væ¶7^Bfö'^B5G^V6¶ôgV'dÆöw^R
input.txt
just some example text, just some example text
some example text
example text, just some example text
$inFile = "input.txt";
$outFile = "output.txt";
$data = array();
$ftm = fopen($outFile, "w+");
$fh = fopen($inFile, "r");
$data = file($inFile);
foreach ($data as $key => $value)
{
$row = $value;
$str_length = strlen($row);
if ($str_length > 10)
{
$width = strlen($row)/2;
$wrapped = wordwrap($row, $width);
fwrite($ftm, $wrapped);
}
else
{
fwrite($ftm, $row);
}
}
fclose($fh);
How can I add a newline \n to the center position of each line?
//Related:
$wrapped = wordwrap($row, $width, '\N');
I'm not sure if this is what you're expecting, but it works given supplied text:
just some example text
some example text
example text
which results to a written file as: (if using '\n')
just some\nexample\ntext
some\nexample\ntext
example\ntext
(EDIT) and as:
just some
example
text
some
example
text
example
text
(if using "\n") which will result having no spaces at the end of each line.
PHP
<?php
$inFile = "input.txt";
$outFile = "output.txt";
$data = array();
$ftm = fopen($outFile, "w+");
$fh = fopen($inFile, "r");
$data = file($inFile);
foreach ($data as $key => $value)
{
$newline = "\n"; // writes to file with no spaces at the end of each line
// $newline = '\n'; // use single quotes if wanting to write \n in the file
$row = $value;
$str_length = strlen($row);
if ($str_length > 10)
{
$width = strlen($row) / 2;
$wrapped = wordwrap($row, $width, $newline);
fwrite($ftm, $wrapped);
}
else
{
fwrite($ftm, $row);
}
}
fclose($fh);
$find = '{<p>something</p>}';
$str1 = "<p>{<p>something</p>}</p>\r\ntext<p>something else</p>";
// or
$str2 = "<p>something</p>\r\n{<p>something</p>}aa<p>t</p>\r\ntext<p>something else</p>";
Basically, $find can be anywhere in the string. New lines delimiter is "\r\n".
I need to find $find in the $str and remove specific html tags around $find in that specific string line. No tags should be removed from $find.
Expected output would be
// For $str1
$str1 = "{<p>something</p>}\r\ntext<p>something else</p>";
// For $str2
$str2 = "<p>something</p>\r\n{<p>something</p>}aat\r\ntext<p>something else</p>";
The string might be very long, so no regex solutions please.
What I have figured out:
$pos = strpos($str, $find);
if ($pos !== false) {
$contentLength = strlen($str);
$lineStart = (int)strrpos($str, "\r\n", -$contentLength+$pos); // cast false to 0 (start of string)
$lineEnd = strpos($str, "\r\n", $pos);
if ($lineEnd === false)
$lineEnd = strlen($str);
$lineLength = $lineEnd-$lineStart;
if ($lineLength < 0)
return;
var_dump(substr($str, $lineStart, $lineLength));
}
Which dumps that specific line in the string.
My final solution:
function replace($find, $str, $replace) {
$pos = strpos($str, $find);
if ($pos !== false) {
$delim = "\r\n";
$contentLength = strlen($str);
$lineStart = strrpos($str, $delim, -$contentLength+$pos);
if ($lineStart === false)
$lineStart = 0;
else
$lineStart += strlen($delim);
$lineEnd = strpos($str, $delim, $pos);
if ($lineEnd === false)
$lineEnd = strlen($str);
$lineLength = $lineEnd - $lineStart;
$line = substr($str, $lineStart, $lineLength);
$posLine = strpos($line, $find); // Where $find starts
$findLength = strlen($find);
$line = substr_replace($line, '', $posLine, $findLength); // Remove $find from $line
$begin = replaceTags(substr($line, 0, $posLine));
$end = replaceTags(substr($line, $posLine));
return substr_replace($str, $begin.$replace.$end, $lineStart, $lineLength);
}
}
function replaceTags($str) {
return str_replace(array('<p>', '</p>'), '', $str);
}
echo replace($find, $str, $replace);
I'm guessing it's fgets, but I can't find the specific syntax. I'm trying to read out (in a string I'm thinking is easier) the last line added to a log file.
The simplest naive solution is simply:
$file = "/path/to/file";
$data = file($file);
$line = $data[count($data)-1];
Though, this WILL load the whole file into memory. Possibly a problem (or not). A better solution is this:
$file = escapeshellarg($file); // for the security concious (should be everyone!)
$line = `tail -n 1 $file`;
This looks like it is what you are looking for:
tekkie.flashbit.net: Tail functionality in PHP
It implements a function that uses fseek() with a negative index to roll up the file from the end. You can define how many lines you want to be returned.
The code also is available as a Gist on GitHub:
// full path to text file
define("TEXT_FILE", "/home/www/default-error.log");
// number of lines to read from the end of file
define("LINES_COUNT", 10);
function read_file($file, $lines) {
//global $fsize;
$handle = fopen($file, "r");
$linecounter = $lines;
$pos = -2;
$beginning = false;
$text = array();
while ($linecounter > 0) {
$t = " ";
while ($t != "\n") {
if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true;
break;
}
$t = fgetc($handle);
$pos --;
}
$linecounter --;
if ($beginning) {
rewind($handle);
}
$text[$lines-$linecounter-1] = fgets($handle);
if ($beginning) break;
}
fclose ($handle);
return array_reverse($text);
}
$fsize = round(filesize(TEXT_FILE)/1024/1024,2);
echo "<strong>".TEXT_FILE."</strong>\n\n";
echo "File size is {$fsize} megabytes\n\n";
echo "Last ".LINES_COUNT." lines of the file:\n\n";
$lines = read_file(TEXT_FILE, LINES_COUNT);
foreach ($lines as $line) {
echo $line;
}
define('YOUR_EOL', "\n");
$fp = fopen('yourfile.txt', 'r');
$pos = -1; $line = ''; $c = '';
do {
$line = $c . $line;
fseek($fp, $pos--, SEEK_END);
$c = fgetc($fp);
} while ($c != YOUR_EOL);
echo $line;
fclose($fp);
This is better, since it does not load the complete file into memory...
Set YOUR_EOL to your correct line endings, if you use the same line endings as the default line endings of the OS where your script resides, you could use the constant PHP_EOL.
function seekLastLine($f) {
$pos = -2;
do {
fseek($f, $pos--, SEEK_END);
$ch = fgetc($f);
} while ($ch != "\n");
}
-2 because last char can be \n
You either have to read the file in line by line and save the last read line to get it.
Or if on unix/linux you might consider using the shell command tail
tail -n 1 filename
This one wont break for a 1 or 0 line file.
function readlastline($fileName)
{
$fp = #fopen($fileName, "r");
$begining = fseek($fp, 0);
$pos = -1;
$t = " ";
while ($t != "\n") {
fseek($fp, $pos, SEEK_END);
if(ftell($fp) == $begining){
break;
}
$t = fgetc($fp);
$pos = $pos - 1;
}
$t = fgets($fp);
fclose($fp);
return $t;
}
If you want to read a file line by line the file function reads the contents of a file, line by line and returns each line as an element of an array.
So you could do something simple like:
$lines = file('log.txt');
$lastLine = array_pop($lines);
...Why just read the last line?
function readLines($fp, $num) {
$line_count = 0; $line = ''; $pos = -1; $lines = array(); $c = '';
while($line_count < $num) {
$line = $c . $line;
fseek($fp, $pos--, SEEK_END);
$c = fgetc($fp);
if($c == "\n") { $line_count++; $lines[] = $line; $line = ''; $c = ''; }
}
return $lines;
}
$filename = "content.txt";
$fp = #fopen($filename, "r");
print_r(readLines($fp, 2));
fclose($fp);
#unique_stephen, your answer is flawed. PHP fseek returns 0 for success and -1 for failure. Storing the result in $begining (sic) and then later using it in a filter for ftell() isn't correct. If my reputation were higher I would have voted you down and left a comment. Here is a modified version of unique_stephen's function.
function readlastline($fileName)
{
$fp = #fopen($fileName, "r");
if (fseek($fp, 0) == -1)
exit('Cannot seek to beginning of the file');
$pos = -1;
$t = " ";
while ($t != "\n") {
if (fseek($fp, $pos, SEEK_END) == -1)
exit('Cannot seek to the end of the file');
if (ftell($fp) == 0) {
break;
}
$t = fgetc($fp);
$pos = $pos - 1;
}
$t = fgets($fp);
fclose($fp);
return $t;
}
NOTE: PHP's fseek cannot manage to seek to the end of files larger than PHP_MAX_INT which is 32bit signed even on 64bit binaries.
function readlastline($fileName)
{
$fp = #fopen($fileName, "r");
$begining = fseek($fp, 0);
$pos = -1;
$t = " ";
while ($t != "\n") {
fseek($fp, $pos, SEEK_END);
if(ftell($fp) == $begining){
break;
}
$t = fgetc($fp);
$pos = $pos - 1;
}
$t = fgets($fp);
fclose($fp);
return $t;
}