changing new line to <br> in text area - php

My problem is pretty simple. I want to change new lines in text area to <br> tags BUT I need the final string to be one-line text. I tried using nl2br function but as a result I get string with <br> tags and new lines. I also tried to simply replace &#013 or &#010 symbols with <br> using str_replace but it doesn't work.
Here is sample of my latest code:
Godziny otwarcia: <textarea name="open" rows="3" cols="20">'."$openh".'</textarea>
<input type="submit" name="openb" value="Zmień"/><br>
if($_POST['openb']) {
$open = $_POST['open'];
str_replace('&#010', '<br>', $open);
change_data(21, $open);
}
The $openh is result of this:
$tab = explode('<br>', $openh);
$openh = null;
for($i=0;$i<count($tab);$i++)
$openh = $openh . $tab[$i] . '&#013';
(yes, I know i could use str_replace, don't ask why I did it this way)
and the original $openh is $openh = 'Pon-pt 9:00-17:00<br>Środa 12:00-17:00'
Also you may want to see my change_data function as it is connected to why i need the string to be in one line, so here it is:
function change_data($des_line, $data) {
$file = 'config.php';
$lines = file($file);
$i=1;
foreach($lines as $line_num => $line) {
$wiersz[$i] = $line;
$i++;
}
$change = explode("'", $wiersz[$des_line]);
$wiersz[$des_line] = $change[0] . "'" . $data . "'" . $change[2];
$i = 1;
$f = fopen($file, w);
while($i <= count($wiersz)) {
fwrite($f, $wiersz[$i]);
$i++;
}
fclose($f);
header('location: index.php?p=admin');
}
I'm not PHP specialist so sometimes I do things little "hard" way.. I had huge problems with reading file config.php line by line and these are results of my few-hours effort :(

have you tried the php constant PHP_EOL? in you str_replace code?
$open=str_replace(PHP_EOL,"<br>",$_POST["open"]);

There is a ready made PHP function for that named nl2br
Source: https://stackoverflow.com/a/16376133/469161

Related

including leading whitespaces when using fgets in php

I am using PHP to read a simple text file with the fgets() command:
$file = fopen("filename.txt", "r") or exit('oops');
$data = "";
while(!feof($file)) {
$data .= fgets($file) . '<br>';
}
fclose($file);
The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:
$data = str_replace(" ", " ", $data);
Not sure where to go from here.
Thanks in advance,
Doug
UPDATE:
The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.
Function fgets() grabs the whitespaces. I don't know what you are exactly doing with the $data variable, but if you simply display it on a HTML page then you won't see whitespaces. It's because HTML strips all whitespaces. Try this code to read and show your file content:
$file = fopen('file.txt', 'r') or exit('error');
$data = '';
while(!feof($file))
{
$data .= '<pre>' . fgets($file) . '</pre><br>';
}
fclose($file);
echo $data;
The PRE tag allows you to display $data without parsing it.
Try it with:
$data = preg_replace('/\s+/', ' ', $data);
fgets should not trim whitespaces.
Try to read the file using file_get_contents it is successfully reading the whitespace in the begining of the file.
$data = file_get_contents("xyz.txt");
$data = str_replace(" ","~",$data);
echo $data;
Hope this helps
I currently have the same requirement and experienced that some characters are written as a tab character.
What i did was:
$tabChar = ' ';
$regularChar = ' '
$file = fopen('/file.txt');
while($line = fgets($file)) {
$l = str_replace("\t", $tabChar, $line);
$l = str_replace(" ", $regularChar, $line);
// ...
// replacing can be done till it matches your needs
$lines .= $l; // maybe append <br /> if neccessary
}
$result = '<pre'> . $lines . '</pre>';
This one worked for me, maybe it helps you too :-).

Combining two text files with PHP - ForEach loops

I'm completely puzzled where to even start on this, but I need to provide a list of keywords in file A and then the same in list B.
With these too files I want to append the lines in A foreach line in file B
For example:
File A:
line1
line2
line3
File B:
test1
test2
test3
Output to a combined.txt file:
line1test1
line2test1
line3test1
line1test2 ... and so on
If you could provide me the portions of the script to research, a sample script, or even a working way to do it. I would greatly appreciate it.
Per request, here is my sample code:
<?php
$file1 = 'keywords.txt';
$file2 = 'topics.txt';
$combined = 'combined.txt';
$keywords = fopen("keywords.txt", "rb");
$topics = fopen("topics.txt", "rb");
$front = explode($topics);
$back = explode($topics);
while (!feof($keywords) ) {
file_put_contents($combined, . $front ."". $back . "\n");
fclose($keywords & $topics);
}
?>
Hope this helps. Comments are sprinkled throughout the code, which I hope is sufficient explanation as to what I'm doing.
<?php
// Open keywords file for reading
$keywords_file = 'keywords.txt';
$keywords_fh = fopen($keywords_file, 'r');
// Get line by line from keywords file, push into $keywords array
// Make sure to trim each line from fgets, to strip off \n at end.
$keywords = array();
while ($line = trim(fgets($keywords_fh))) {
array_push($keywords, $line);
}
fclose($keywords_fh);
// Open topics file for reading
$topics_file = 'topics.txt';
$topics_fh = fopen($topics_file, 'r');
// Get line by line from topics file, push into $topics array
// Make sure to trim each line from fgets, to strip off \n at end.
$topics = array();
while ($line = trim(fgets($topics_fh))) {
array_push($topics, $line);
}
fclose($topics_fh);
// Open combined file for writing
$combined_file = 'combined.txt';
$combined_fh = fopen($combined_file, 'w');
// Iterate through each keyword.
// For each iteration, iterate through each topic.
// Write the concatenation of keyword and topic to file.
foreach ($keywords as $keyword) {
foreach ($topics as $topic) {
fwrite($combined_fh, "$keyword$topic\n");
}
}
fclose($combined_fh);
Here are some links to PHP documentation for some of the key functions I used:
fopen
trim
fgets
fwrite
fclose
$f1 = explode("\n",file_get_contents("fileA.txt"));
$f2 = explode("\n",file_get_contents("fileB.txt"));
foreach ($f1 as $key => $value) {
$f3[] = $value.$f2[$key];
}
file_put_contents("fileC.txt", implode("\n",$f3));

Reading text after a certain character in php

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
?>

Parsing file in PHP; how to detect newlines?

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);

PHP get array of words from txt file

I have a text file with spam words. I want to have an array filled with those words.
I've tried doing:
$fp = #fopen("../files/spam.txt",'rb');
$words = fgetcsv($fp,100,"\n");
but it doesn't work (words only has the first letter of the txt file in it first cell).
do you how to do this?
EDIT:
the .txt file looks like this:
yahoo
google
msn
blah
blah
EDIT:
I DONT KNOW WHAT IS A CSV FILE! THIS IS A TEXT FILE! I JUST GIVE AN EXAMPLE.
please could some1 help me it looks really easy, i just dont understand.
That is not a CSV file. CSV stands for comma separated values. You have no commas!
$spam_words = file('../files/spam.txt', FILE_IGNORE_NEW_LINES);
All you need to do is:
$words = file('./files/spam.txt',FILE_IGNORE_NEW_LINES);
$artic = array(); //create a array
$directory = "/var/www/application/store/"; //define path
$files1 = scandir($directory); //scan the directory
$c = count($files1); //count the files the directory
print $c; //print it
for($i = 2; $i < $c; $i++) {
print "<br />" . $files1[$i];
$f = $directory . $files1[$i];
print $f . "<br />";
$h = fopen($f, 'r') or die("cannot open a file!!". $f);
$line1 = fgets($h);
list($id, $idval) = explode("\t\t", $line1);
print "$id";
}
How about splitting the string you read from the file into an array?
split() function definition.
$string = "Niagara Becks Corn";
$array = split(" ", $string);
# ["Niagara", "Becks", "Corn"]
Use the 'file' function to read a PHP file from the disk into an array. See the manual here: http://php.net/manual/en/function.file.php
Try this
$file = file_get_contents('spam.txt');
$file_words = explode(" ", $file);
$file_count = count($file_words);
for ($i=0; $i < $file_count; $i++){
echo $file_words[$i] . "<br />";
}
Your spam.txt file should look like this:
yahoo msn google

Categories