I've got a problem where I'm trying to read a text file like this:
Joe
Johnson
Linus
Tourvalds
and while parsing it in php, I need to be able to detect the newlines. I'm trying to correctly define $newline. I'm looping through the array of lines in the $file variable.
while($line = next($file))
if($line = $newline)
echo "new line";
The problem is that I can't seem to match the newline character. I know that it is actually showing up in the $file array, because this:
while($line = next($file))
echo $line;
outputs the file verbatim, with newlines and all. I've already tried "\n", " ", and I'm not sure what to try next. A little help?
$file = file("path/to/file.txt");
// Incase you need to call it multiple times ...
function isNewLine($line) {
return !strlen(trim($line));
}
foreach ($file as $line) {
if (isNewLine($line)) {
echo "new line<br/>";
}
}
Maybe something like this would work for you?
while($line = next($file)) {
if(in_array($line, array("\r", "\n", "\r\n"))) {
echo "new line";
}
}
I think this solution may help you guys. This works if you are parsing csv that is generated from Mac or windows. Reading csv with multilines created in Mac, gives problem i.e. you cannot read each line in a loop but all csv data is read as single line.
This problem is solved by following solution:
//My CSV contains only one column
$fileHandle = fopen("test.csv",'r');
$codesArray = array();
count = 0;
while (!feof($fileHandle) ) {
$line = fgetcsv($fileHandle);
if($line[0]!="") {
$data = str_replace("'", "", (nl2br ($line[0])));
$dataArray = explode('<br />' ,$data );
foreach($dataArray as $data) {
$codesArray[] = trim($data);
}
}
}
echo "<pre>";
print_r($codesArray);
Related
I was trying to get the text starting from css:{(some text...)} up to the ending bracket only, not including the texts below in another text file using php.
test.sample
just a sample text
css:{
"css/test.css",
"css/test2.css"
}
sample:text{
}
I'm using vscode/sublime search and replace tool to test my regex syntax and nothing is wrong, I successfully get the text that I want including all the new lines and spaces inside, but when i tried to apply it on php, the regex that I created doesn't work, it cannot find the text that im looking for.
here is my code:
myphp.php
$file = file_get_contents("src/page/test.sample");
echo $file . "<br>";
if (preg_match_all("/(css\s*\n*:\s*\n*\{\s*\n*)+((.|\n\S)*|(.|\n\s)*)(\n*)(\}\W)$/", $file)) {
echo "Success";
} else {
echo "Failed!";
}
This is my regex that I just created.
(css\s*\n*:\s*\n*{\s*\n*)+((.|\n\S)|(.|\n\s))(\n*)(}\W)$
Please help me, Im open for any suggestion, Im a newbie on regular expression, Im lacking on knowledge about the logic of it.
thanks.
Try this my friend:
<?php
$file = "testfile.php"; // call the file
$f = fopen($file, 'rb'); // open the file
$found = false;
while ($line = fgets($f, 1000)) { // read every line of the file
if ($found) {
echo $line;
continue;
}
if (strpos($line, "css:") !== FALSE) { // if we found the word 'css:' we print everything after that
$found = true;
}
}
Hey guys I found the solution! base on the answer of #alex
Dont really know if I am implementing this right.
Here is my code
$src = "src/page/darwin.al"; //get the source file
$file = fopen($src,"rb"); //I dont really know what 'rb' means, I guess it simply means, 'not a commong text file'?, search for it!
$found = false;
$css = false;
while($line = fgets($file)){ //read every line of text and assign that line of text in a variable $line
if(strpos(preg_replace("/\s*/", "", $line), "css:{") === 0){ //if the current line is == 'css:{' <the thing that Im looking for,
$found = true;
$css = true;
}elseif($css && strpos(preg_replace("/\s*/", "", $line),"}") === 0){ //If we are still inside the css block and found the '{'
echo $line;
break;
}
if ($found) {
echo preg_replace("/\s*/", "", $line); //remove every whitespace!
}
}
fclose($file);//close the file
The numbers in my file are 5X5:
13456
23789
14789
09678
45678
I'm trying to put it into this form
array[0]{13456}
array[1]{23789}
array[2]{14789}
array[3]{09678}
array[4]{45678}
My code is:
$fileName = $_FILES['file']['tmp_name'];
//Throw an error message if the file could not be open
$file = fopen($fileName,"r") or exit("Unable to open file!");
while ($line = fgets($file)) {
$digits .= trim($line);
$members = explode("\n", str_replace(array("\r\n","\n\r","\r"),"\n",$digits));
echo $members;
The output I'm getting is this:
ArrayArrayArrayArrayArray
fgets gets a line from the file pointer, so theoretically there should be no "\r" or "\n" characters in $line. explode will still work, even if the delimiter is not found. You'll just end up with an array with one item, the entire string. You can't echo an array, though. (That's why you're seeing Array for each line; it's the best PHP can do when you use echo on an array.)
If I were you, I would rather just use file() instead.
$members = array_map('trim', file($fileName, FILE_IGNORE_NEW_LINES));
With the example file you showed, this should result in
$members = ['13456', '23789', '14789', '09678', '45678'];
You can simply put the lines into an array and use print_r instead of echo to print that array
while ($line = fgets($file)) {
$members[] = $line;
}
print_r($members);
It should depend on the file that you are dealing with.
FileType:
text -> fgets($file)
CSV -> fgetcsv($file)
I'm a beginner in this field so please excuse any mistakes I make in terms or language, I'm having issues with a program that I inherited (and don't fully understand) and am looking for a bit of help.
It's built in PHP and was working on a Mac but is not working on a Windows machine - they're both running the same version of PHP (7.1.0.) The program is reading a csv line by line but on windows the loop stops after the first iteration / line - after the actual first line (which are column headers) is skipped.
This sets up the array and is working fine on both machines:
$firstRow = null;
$i = 0;
$file = null;
$currentfig = null;
foreach ($relarray as $row) {
if($i == 0) {
echo "first line";
$firstRow = $row;
}
else {
// check which file is available
if($currentfig != $row[0]) {
$currentfig = $row[0];
if($file != null)
fclose($file);
$file = fopen("csv/".$currentfig.".csv", "w");
mkdir ("folders/" . $currentfig);
}
$csvLine = fputcsv($file, $row);
echo "others";
echo "<dl>";
for($o = 0; $o < count($row); $o++) {
echo "<dt>$firstRow[$o]</dt><dd>$row[$o]</dd>";
}
echo "</dl>";
}
$i++;
}
Then this creates the line by line process on the array:
if($csvFile == null) {
$csvFile = 'TempSheet.csv';
}
echo "<h1>Processing $csvFile </h1>";
$csvData = file_get_contents($csvFile);
$lines = explode(PHP_EOL, $csvData);
$relarray = array();
foreach ($lines as $line) {
if (!$line){
$line = null;
}
else {
$relarray[] = str_getcsv($line);
echo "rel array is";
print_r($relarray);
}
}
At this point, on the mac it creates and prints a series of arrays, one for each row, all contained in one larger array. On windows it creates just one array with
all of the elements from all rows within it.
I then take individual elements from this above one using a variety of these:
foreach ($relarray as $row) {
$subtitles = $row[18];
echo $subtitles . "<br />";
$subtitles = str_replace("&", "&", str_replace("\r\n", "\n", $subtitles));
$starray[]=$subtitles;
}
Here ^ on a Mac printing the '$starray' displays the full 5 values whereas on Windows it only displays the initial one.
I've tried a few things to no avail; including using variations of line break signifiers and changing the php.ini settings as suggested here: CSV new Line Character
I'd be very grateful for any suggestions or help, please let me know if you need further information.
Thanks
$lines = explode(PHP_EOL, $csvData);
Your problem is that the CSV file is parsed using PHP_EOL as line-ending character, but this constant has different values depending on the environement running the code (\r\n on Windows and \r or \n on Mac depending on pre/post OSX).
If your file has been created/saved on a Mac, it must've been saved with a \n at the end of each line (assuming the Mac is running a post-OSX version), and Windows search for a \r\n as the line end.
The consequence of this is that Windows cannot find its own line-ending characater and thinks it only has 1 big line containing all the data.
In addition to that, changing auto_detect_line_endings doesn't work in you case because you use file_get_contents which does not read line by line but the whole file at once and doesn't care about the line-ending.
So, what you could try is to enable auto_detect_line_endings and replace your following piece of code:
$csvData = file_get_contents($csvFile);
$lines = explode(PHP_EOL, $csvData);
$relarray = array();
foreach ($lines as $line) {
if (!$line){
$line = null;
}
else {
$relarray[] = str_getcsv($line);
echo "rel array is";
print_r($relarray);
}
}
By something like:
$csvFileHandle = fopen($csvFile, 'r');
$relarray = array();
if($csvFileHandle) {
while($csvLine = fgetcsv($csvFileHandle)) {
$relarray[] = $csvLine;
}
fclose($csvFileHandle );
}
Which will actually make use of the auto_detect_line_endings configuration and will correctly detect you CSV file endings + split each line in fields ($csvLine) and add them to $relarray.
Okay so I have a text file and inside of the text file I have these lines:
IP = 127.0.0.1
EXE = Client.exe
PORT = 8080
TITLE = Title
MAINT = False
MAINT-Message = This is the message.
what I am wanted to do is get the 'False' part on the fifth line.
I have the basic concept but I can't seem to make it work. This is what I have tried:
<?php
$file = file_get_contents('LauncherInfo.txt');
$info = explode(' = ', $file);
echo $info[5];
?>
And with this I get a result but when I echo $info[5] it gives me 'False Maint-Message' so it splits it but it only splits at the = sign. I want to be able to make it split at the where I have pressed enter to go onto the next line. Is this possible and how can I do it?
I was thinking it would work if I make it explode on line one and then do the same for the second line with a loop until it came to the end of the file? I don't know how to do this though.
Thanks.
I think you're looking for the file(), which splits a file's contents into an array of the file's lines.
Try this:
$file = file('LauncherInfo.txt');
foreach ($file as $line) {
if ($line) {
$splitLine = explode(' = ',$line);
$data[$splitLine[0]] = $splitLine[1];
}
}
echo $data['MAINT'];
Just in case you were curious, since I wasn't aware of the file() function. You could do it manually like this
<?php
$file = file_get_contents('LauncherInfo.txt');
$lines = explode("\n", $file);
$info=array();
foreach($lines as $line){
$split=explode(' = ',$line);
$info[]=$splitline[1];
}
echo $info[5];//prints False
?>
I have a text file that maintains a list of words.
What I am trying to do is pass a string(sentence) to this function and remove the word from the string if it exists in the text file.
<?php
error_reporting(0);
$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning";
common_words($str1);
function common_words($string) {
$file = fopen("common.txt", "r") or exit("Unable to open file!");
$common = array();
while(!feof($file)) {
array_push($common,fgets($file));
}
fclose($file);
$words = explode(" ",$string);
print_r($words);
for($i=0; $i <= count($words); $i+=1) {
for($j=0; $j <= count($common); $j+=1) {
if($words[$i] == $common[$j]){
unset($words[$i]);
}
}
}
}
?>
It doesn't seem to work however. The common words from the string are not being removed. instead I am getting the same string with the one I started.
I think I am doing the loop wrong. What is the correct approach and what am I doing wrong?
on the line
if($words[$i] == $common[$j]){
change it to
if(in_array($words[$i],$common)){
and remove the second for loop.
Try using str_replace():
foreach($common as $cword){
str_replace($cwrod, '', $string); //replace word with empty string
}
Or in full:
<?php
error_reporting(0);
$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning";
common_words($str1);
function common_words(&$string) { //changes the actual string passed with &
$file = fopen("common.txt", "r") or exit("Unable to open file!");
$common = array();
while(!feof($file)) {
array_push($common,fgets($file));
}
fclose($file);
foreach($common as $cword){
str_replace($cword, '', $string); //replace word with empty string
}
}
?>