convert string fetched with php nl2dr into array [duplicate] - php

I have form in html where user can put the text in text area.
I save the content of text area into MySQL database (in field of type TEXT).
Then I somewhere in my aplication I need load that text and put it into array where in each index will be one line of the text.
<textarea rows="10" cols="80">
Row one
Row two
Row tree
</textarea>
array (output in "php pseudocode"):
$array = array();
$array[0] = Row one;
$array[1] = Row two;
$array[2] = Row tree;
How I do it:
I save it to db then I load it and use:
$br = nl2br($string,true);
$array = explode("<br />", $br);
The reason why I use nl2br is I want to avoid problems with end of lines of the text from different platforms. I mean /n or /r/n.
But in my solution must be an error somewhere cause it doesn't work (an array $array is empty).
Better solution would be probably somehow split it into array using explode or something like that with pattern for line breaks but here is again the problem from beginning with line breaks which I don't know how to solve (problems with \n or \r\n).
Can anybody give me an advice? Thanks.

I'd suggest you skip the nl2br until you're ready to actually send the data to the client. To tackle your problem:
// $string = $get->data->somehow();
$array = preg_split('/\n|\r\n/', $string);

When you receive the input in your script normalize the end-of-line characters to PHP_EOL before storing the data in the data base. This tested out correctly for me. It's just one more step in the "filter input" process. You may find other EOL character strings, but these are the most common.
<?php // RAY_temp_user109.php
error_reporting(E_ALL);
if (!empty($_POST['t']))
{
// NORMALIZE THE END-OF-LINE CHARACTERS
$t = str_replace("\r\n", PHP_EOL, $_POST['t']);
$t = str_replace("\r", PHP_EOL, $t);
$t = str_replace("\n", PHP_EOL, $t);
$a = explode(PHP_EOL, $t);
print_r($a);
}
$form = <<<FORM
<form method="post">
<textarea name="t"></textarea>
<input type="submit" />
</form>
FORM;
echo $form;
Explode on PHP_EOL and skip the nol2br() part. You can use var_dump() to see the resulting array.

Related

Script to remove whitespace and list items

I'm trying to create a script which would take an input of formatted text (more specifically a copy and pasted list from a word document, likely bullet pointed or numbered) in a text-box input.
After looking into this I have tried using str_replace and preg_replace but im struggling to get the correct pattern to do what i want here. I'm also unsure on what I can use to 'target' the tabbed space in my pattern. I've tried various ASCII codes with no success (e.g )
Apologies accidentally hit enter while adding tags
Examples of pre-script data:
1. Text
2. Text
3. Text
4. Text
While it doesn't show clearly here, there is a large tabbed space between the numbering and text when pasting.
Post-script:
Text
Text
Text
Text
<?php
$output_space = "";
$output_tab = "";
if(isset($_POST['submit'])) {
$lines = explode('<br />', nl2br($_POST['input']));
foreach($lines as $line){
$tbl_space = explode(" ", $line);
$tbl_tab = explode("\t", $line);
array_shift($tbl_space); // remove first element of the array (everything before the first tab)
array_shift($tbl_tab);
$output_space .= trim(implode(" ", $tbl_space))."\r\n";
$output_tab .= trim(implode("\t", $tbl_tab))."\r\n";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="deformat">
Formatted data <textarea rows="4" cols="50" name="input" form="deformat" placeholder="pasted formatted text here">
</textarea>
Deformatted data (spaces) <textarea rows="4" cols="50" name="output" form="deformat"><?=$output_space?>
</textarea>
Deformatted data (tab)<textarea rows="4" cols="50" name="output" form="deformat"><?=$output_tab?>
</textarea>
<input type="submit" name="submit" value="Clean my data!">
</form>
Assuming you're pasting the content in a TextArea and submitting it, you may well lose the correct tabulation in doing so, so instead use the bullets. My PHP is somewhat rusty, so check the code before you use it, but something along the lines of this will work.
$text = htmlspecialchars($_POST['myFormElement']);
$lines = explode(PHP_EOL, $text);
$bullets = array();
foreach ($lines as $line)
{
preg_match("/([^\s]+)\s+(\w*)/", $line,$captured);
if (count($captured) > 1 ) {
if (strcmp($captured[1], end($bullets))) {
if (count($bullets) > 1 && !strcmp($bullets[count($bullets)-2],$captured[1])) {
echo '</ul>';
array_pop($bullets);
} else {
echo '<ul>';
array_push($bullets, $captured[1]);
}
}
echo "<li>$captured[2]</li>";
}
}
while (count($bullets)) {
echo "</ul>";
array_pop($bullets);
}
Use something like this:
$arSingleLine = explode(PHP_EOL, $yourPostString);
$arRet = array();
foreach ($arSingleLine as $sSingle)
{
$arRet[] = preg_replace('/^.+\s+/', '', $sSingle);
}
// $arRet holds now every single fixed line...
Maybe PHP_EOL does not match your client line ending. For splitting every line ending from a single line of code just use preg_split and the line endings \n \r and \r\n for UNIX, OS X and Windows line breaks.

Handling new lines in php

I have form in html where user can put the text in text area.
I save the content of text area into MySQL database (in field of type TEXT).
Then I somewhere in my aplication I need load that text and put it into array where in each index will be one line of the text.
<textarea rows="10" cols="80">
Row one
Row two
Row tree
</textarea>
array (output in "php pseudocode"):
$array = array();
$array[0] = Row one;
$array[1] = Row two;
$array[2] = Row tree;
How I do it:
I save it to db then I load it and use:
$br = nl2br($string,true);
$array = explode("<br />", $br);
The reason why I use nl2br is I want to avoid problems with end of lines of the text from different platforms. I mean /n or /r/n.
But in my solution must be an error somewhere cause it doesn't work (an array $array is empty).
Better solution would be probably somehow split it into array using explode or something like that with pattern for line breaks but here is again the problem from beginning with line breaks which I don't know how to solve (problems with \n or \r\n).
Can anybody give me an advice? Thanks.
I'd suggest you skip the nl2br until you're ready to actually send the data to the client. To tackle your problem:
// $string = $get->data->somehow();
$array = preg_split('/\n|\r\n/', $string);
When you receive the input in your script normalize the end-of-line characters to PHP_EOL before storing the data in the data base. This tested out correctly for me. It's just one more step in the "filter input" process. You may find other EOL character strings, but these are the most common.
<?php // RAY_temp_user109.php
error_reporting(E_ALL);
if (!empty($_POST['t']))
{
// NORMALIZE THE END-OF-LINE CHARACTERS
$t = str_replace("\r\n", PHP_EOL, $_POST['t']);
$t = str_replace("\r", PHP_EOL, $t);
$t = str_replace("\n", PHP_EOL, $t);
$a = explode(PHP_EOL, $t);
print_r($a);
}
$form = <<<FORM
<form method="post">
<textarea name="t"></textarea>
<input type="submit" />
</form>
FORM;
echo $form;
Explode on PHP_EOL and skip the nol2br() part. You can use var_dump() to see the resulting array.

Using PHP to Seperate Results of a txt file

I am trying to display the last 10 lines of a File and from there take those results and break them down to 10 individual lines..
Currently the code I have found from examples is:
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
echo implode($lastfifteenlines, "\n")
It display's the 10 items I need however it does not break them down onto individual lines the current results are:
1.0.0.11 1.0.0.12 1.0.0.13 1.0.0.14 1.0.0.15
I need that to instead display as:
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
Thanks in Advance for the Asistance!
\n is plain whitespace in html.
use echo implode("<br>", $lastfifteenlines) or put them in to separate divs, use a list (ul+li), etc..
use the explode function, like this
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
$impfile = implode($lastfifteenlines, '\n');
$lines = explode('\n', $impfile);
foreach ($lines as $line){
echo $line."<br>";
}
outpu will be
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
i hope that's what you want :)
Your code works fine. You just can't see the line breaks because HTML doesn't treat them as line breaks.
See the HTML source code in your browser to see the line breaks.
Possible solution
echo <pre> and </pre> tags before and after the implode.
Add header("Content-Type: text/plain"); before any output. It will cause the browser to parse the document as a text file and not HTML (note that no HTML tags will be parsed by the browser)
implode the array with a different string, <br>, which will cause a line break in HTML.
Also, your syntax is wrong, it's
implode($glue, $pieces);
And not
implode($pieces, $glue);

Why is it starting a new line before it should in PHP array?

I'm having a problem with arrays and file writing, what I want to do is take one file, and copy it onto another file, except with formatting added to it.
To be specific, this:
Line 1
Line 2
Line 3
Would become this:
<br /><hr />Line 1
<br /><hr />Line 2
<br /><hr />Line 3
And I've sorta done that, but something weird happens. Instead of formatting all on one line, it linebreaks and keeps going. Like this
<br />1
THE END<br />7
THE END<br />0
THE END<br />Red
THE END<br />Silent
THE END<br />No ChangesTHE END
My code for this is:
<?php
$filename1 = "directorx_OLDONE.txt";
$filename2 = "directorx_NEWONE.txt";
$file1 = fopen($filename1, "r") or exit ("No");
$file2 = fopen($filename2, "w") or exit ("No");
while (!feof($file1)){
$listArrayf1[] = fgets($file1);
}
fclose($file1);
echo var_dump($listArrayf1) . "<br /><br />";
$entries = count($listArrayf1) - 1;
echo $entries;
for($i=0;$i<=$entries;$i++){
$listArrayf2[] = "<br />".$listArrayf1[$i]."THE END";
fwrite($file2, $listArrayf2[$i]);
}
fclose($file2);
echo var_dump($listArrayf2);
/*
Open file1, r
Open file2, w
While it's not the end of the file, add each line of file1 to an array.
Count the number of lines in file1 and call it Entries. -1 because gotta start at 0.
Make a new array with the values of the old one, but with tags before and after it.
*/
?>
I'm sure there's a better way to accomplish the ultimate goal I'm trying, which is detecting certain words entered into a form, (There's probably a better way than making a formatted and non-formatted copy of what gets entered.) but my PHP vocab is limited and I'd like to figure out the long, prerequisite hard ways before learning how to do em easier.
At first I thought that it was because I was writing the OLDFILE manually, using the return key. So I made a script to write it using \n instead and it changed nothing.
Eh :)
At first, please take a look on var_dump and check what the function is returning (nothing, so correct usage is var_dump( ...); echo "<br />";)
Second, fgets reads string including newline character, so I guess you see in your string something like this:
string( 10) "abcdefghi
"
So you have to remove newline manually for example with trim.
Next, I'd recommend to (at least) take a look at foreach.
So I'd wrote the whole loop as:
foreach( $listArrayf1 as $row){
$row = "<br /><hr />". trim( $row)."THE END";
fwrite($file2, $row);
$listArrayf2[] = $row;
}
You may also use foreach( $listArrayf1 as &$row) and in the end $listArrayf1 will contain exactly the same as $listArrayf2. When you need to preserve all other spaces, you should probably use $row = substr( $row, 0, -1);
btw: you can write normal code, mark it in textarea and by hitting ctrl+k it'll get indented by 4 spaces
fgets returns the newline character at the end of each line as part of its input. That's where your "extra" newline comes from.
Change this
$listArrayf1[] = fgets($file1);
to this:
$listArrayf1[] = rtrim(fgets($file1), "\r\n");
This will remove the newline characters from the end of the return value and make your strings format as intended.
However, as you said yourself you are really doing things in a roundabout way. You could read all of file1 into an array with just
$listArrayf1 = file($filename1);
That's it. No loops, no fopen, no problems with newlines. It pays to look for the most fitting way of doing things.

PHP uploaded text file line breaks issue

I'm working on a simple script that get's a txt file posted to it and then displays the file contents. However, I'm having issues preserving line breaks.
It's being saved with windows notepad, which I think adds the CR LF for each line break, and then uploaded through a PHP form. I can echo the whole file contents but I need a way to split the data into new lines.
I've already tried to do echo str_replace(array("\r\n", "\r", "\n"), '<br />', $file); and nl2br($file). Neither worked.
I'm opening the file with `file_get_contents($_FILES['file']['tmp_name'])'
Thanks.
Have you considered reading the file into an array using the file() function in PHP?
http://php.net/manual/en/function.file.php
Then you can output as needed, but each line will be in a single element of the array.
What works faster for me is to copy paste any text or Excel or HTML table type or newline type of data and paste it into a textarea instead of an inputextbox:
<textarea id="txtArea" name="txtArea" rows="40" cols="170"></textarea>
<br>
<input type="submit" value="split lines into array" />
in the form receiving file:
$txtArea ='';
$txtArea = $_POST['txtArea'];
$TA = $_POST['txtArea'];
$string = $TA;
$array = preg_split ('/$\R?^/m', $string);
// or any of these:
// $array = explode(PHP_EOL,$string);
// $array = explode("\n", $txtArea);
echo "<br>A0: ".$array[0];
echo "<br>A1: ".#$array[1];
echo "<br>A2: ".#$array[2];

Categories