Processing each line of a textarea form in a script - php

I've learned it's possible to trim a string from a textarea and put break tags after it, so each sentence written at a new line in the textbox will also be written at a new line in the PHP file.
This is the snippet:
<html>
<body>
<?php
$text = trim($_POST['textarea']);
$text = nl2br($text);
echo $text;
?>
</body>
</html>
The thing is that my true intentions are:
Use the contents of each line in the textbox for a certain script
Print the contents of each line with the results from the script added all separated by lines.

<?php
$text = trim($_POST['textarea']);
$text = explode ("\n", $text);
foreach ($text as $line) {
echo myFunction($line);
echo "< hr />";
}
?>

The PHP function explode lets you take a string and blow it up into smaller pieces. Store this array for use in other scripts
$str_arr = explode("\n", $_POST['textarea']);
//$str_arr can be used for other script

Related

Echo php code error?

My thing is when I echo my php code it doesnt echo the code it echo's numbers in return I am trying to add a PHP code to my website so every week the text on the website would update from a stored file like quotes.txt. Is there something wrong with my php any suggestions? Here is a screenshot of what happens https://gyazo.com/fba5fc414228b1ab2a79bb877642477a
My Code :
<div class="wrapper">
<div class="teachings">
<h1 id="teach">Teaching's</h1>
<hr>
<?php
$text = file_get_contents("quotes.txt");
$text = trim($text); //This removes blank lines so that your
//explode doesn't get any empty values at the start or the end.
$array = explode(PHP_EOL, $text);
$lineNumber = date('s');
echo "<p>$lineNumber</p>";
?>
<h1>Weekly Teachings :</h1>
<br>
</div>
</div>
You are echoing the currect second value from a date('s') function call
I assume you want to echo the number of lines in the array
$array = explode(PHP_EOL, $text);
$lineNumber = count($array);
echo "<p>$lineNumber</p>";
But if you intended something else, add a comment I I will attempt to change this answer accordingly
RE: Your comment below, then you want to do
echo "<p>{$array[0]}</p>";
What you want to do is
echo $array[$lineNumber];
That will echo the quote whose line number is the week number.

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

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

I need to split text delimited by paragraph tag

$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
I need to split the above into an array delimited by the paragraph tags. That is, I need to split the above into an array with two elements:
array ([0] = "this is the first paragraph", [1] = "this is the first paragraph")
Remove the closing </p> tags as we don't need them and then explode the string into an array on opening </p> tags.
$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
$text = str_replace('</p>', '', $text);
$array = explode('<p>', $text);
To see the code run please see the following codepad entry. As you can see this code will leave you with an empty array entry at index 0. If this is a problem then it can easily be removed by calling array_shift($array) before using the array.
For anyone else who finds this, don't forget that a P tag may have styles, id's or any other possible attributes so you should probably look at something like this:
$ps = preg_split('#<p([^>])*>#',$input);
This is an old question but I was not able to find any reasonable solution in an hour of looking for stactverflow answers. If you have string full of html tags (p tags) and if you want to get paragraphs (or first paragraph) use DOMDocument.
$long_description is a string that has <p> tags in it.
$long_descriptionDOM = new DOMDocument();
// This is how you use it with UTF-8
$long_descriptionDOM->loadHTML((mb_convert_encoding($long_description, 'HTML-ENTITIES', 'UTF-8')));
$paragraphs = $long_descriptionDOM->getElementsByTagName('p');
$first_paragraph = $paragraphs->item(0)->textContent();
I guess that this is the right solution. No need for regex.
edit: YOU SHOULD NOT USE REGEX TO PARSE HTML.
$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
$exptext = explode("<p>", $text);
echo $exptext[0];
echo "<br>";
echo $exptext[1];
//////////////// OUTPUT /////////////////
this is the first paragraph
this is the first paragraph
Try this code:
<?php
$textArray = explode("<p>" $text);
for ($i = 0; $i < sizeof($textArray); $i++) {
$textArray[$i] = strip_tags($textArray[$i]);
}
If your input is somewhat consistent you can use a simple split method as:
$paragraphs = preg_split('~(</?p>\s*)+~', $text, PREG_SPLIT_NO_EMPTY);
Where the preg_split will look for combinations of <p> and </p> plus possible whitespace and separate the string there.
As unnecessary alternative you can also use querypath or phpquery to extract only complete paragraph contents using:
foreach (htmlqp($text)->find("p") as $p) { print $p->text(); }
Try the following:
<?php
$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
$array;
preg_replace_callback("`<p>(.+)</p>`isU", function ($matches) {
global $array;
$array[] = $matches[1];
}, $text);
var_dump($array);
?>
This can be modified, putting the array in a class that manage it with an add value method, and a getter.
Try this.
<?php
$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
$array = json_decode(json_encode((array) simplexml_load_string('<data>'.$text.'</data>')),1);
print_r($array['p']);
?>

Get each line from textarea

<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>
$text = value from this textarea;
How to:
1) Get each line from this textarea ($text) and work with them using foreach()?
2) Add <br /> to the end of each line, except the last one?
3) Throw each line to an array.
Important - text inside textarea can be multilanguage.
Have tried to use:
$text = str_replace('\n', '<br />', $text);
But it doesn't work.
Thanks.
You will want to look into the nl2br() function along with the trim().
The nl2br() will insert <br /> before the newline character (\n) and the trim() will remove any ending \n or whitespace characters.
$text = trim($_POST['textareaname']); // remove the last \n or whitespace character
$text = nl2br($text); // insert <br /> before \n
That should do what you want.
UPDATE
The reason the following code will not work is because in order for \n to be recognized, it needs to be inside double quotes since double quotes parse data inside of them, where as single quotes takes it literally, IE "\n"
$text = str_replace('\n', '<br />', $text);
To fix it, it would be:
$text = str_replace("\n", '<br />', $text);
But it is still better to use the builtin nl2br() function, PHP provides.
EDIT
Sorry, I figured the first question was so you could add the linebreaks in, indeed this will change the answer quite a bit, as anytype of explode() will remove the line breaks, but here it is:
$text = trim($_POST['textareaname']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
}
If you do it this way, you will need to append the <br /> onto the end of the line before the processing is done on your own, as the explode() function will remove the \n characters.
Added the array_filter() to trim() off any extra \r characters that may have been lingering.
You could use PHP constant:
$array = explode(PHP_EOL, $text);
additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution
Old tread...? Well, someone may bump into this...
Please check out http://telamenta.com/techarticle/php-explode-newlines-and-you
Rather than using:
$values = explode("\n", $value_string);
Use a safer method like:
$values = preg_split('/[\n\r]+/', $value_string);
Use PHP DOM to parse and add <br/> in it. Like this:
$html = '<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>';
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('textarea');
//get text and add <br/> then remove last <br/>
$lines = $nodes->item(0)->nodeValue;
//split it by newlines
$lines = explode("\n", $lines);
//add <br/> at end of each line
foreach($lines as $line)
$output .= $line . "<br/>";
//remove last <br/>
$output = rtrim($output, "<br/>");
//display it
var_dump($output);
This outputs:
string ' put returns between paragraphs
<br/>for linebreak add 2 spaces at end
<br/>indent code by 4 spaces
<br/>quote by placing > at start of line
' (length=141)
It works for me:
if (isset($_POST['MyTextAreaName'])){
$array=explode( "\r\n", $_POST['MyTextAreaName'] );
now, my $array will have all the lines I need
for ($i = 0; $i <= count($array); $i++)
{
echo (trim($array[$i]) . "<br/>");
}
(make sure to close the if block with another curly brace)
}
$array = explode("\n", $text);
for($i=0; $i < count($array); $i++)
{
echo $line;
if($i < count($array)-1)
{
echo '<br />';
}
}
$content = $_POST['content_name'];
$lines = explode("\n", $content);
foreach( $lines as $index => $line )
{
$lines[$index] = $line . '<br/>';
}
// $lines contains your lines
For a <br> on each line, use
<textarea wrap="physical"></textarea>
You will get \ns in the value of the textarea. Then, use the nl2br() function to create <br>s, or you can explode() it for <br> or \n.
Hope this helps

Categories