<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
Related
In my database I've
Linetext1 \r\nLinetext2
I then fech data:
while($row = $result->fetch_assoc()) {
$mydata_array = $row['myrow'];
}
then the echo part:
for ($i = 0; $i <5; ++$I){
echo $mydata_array[$i];
}
But it literally output in textarea (and in fpdf) Linetext1 \r\nLinetext2. I did try a string replace as suggested in other questions
echo (str_replace('\r\n', '<br />', $mydata_array[$i]);
but then I literally have
Linetext1 <br />Linetext2
Thanks for your help!
SOLUTION
After Sergey's answer, I used this:
echo (str_replace(array('\r', '\n'), array("", "\n"), $mydata_array[$i]);
PS It's important to use MultiCell and not single Cell
<br /> tags are useless in a textarea, unless it's a rich text editor area (and therefore not exactly a textarea) - it needs \n or \r\n line breaks. FPDF needs \n breaks, too. What you should probably do is to replace the \r and \n literals to actual line breaks:
echo (str_replace(array('\r', '\n'), array("", "\n"), $mydata_array[$i]);
Edit: As per your testing, \r should be wiped out completely, because it only confuses the FPDF without adding any real value.
I have this text : http://pastebin.com/2Zgbs7hi
And i want to be able to remove the HTML code from it and just display the plain text but i want to keep at least one line break where there are currently a few line breaks
i have tried:
$ticket["summary"] = 'pastebin example';
$TicketSummaryDisplay = nl2br($ticket["summary"]);
$TicketSummaryDisplay = stripslashes($TicketSummaryDisplay);
$TicketSummaryDisplay = trim(strip_tags($TicketSummaryDisplay));
$TicketSummaryDisplay = preg_replace('/\n\s+$/m', '', $TicketSummaryDisplay);
echo $TicketSummaryDisplay;
that is displaying as plain text, but it shows it all as one big block of text with no line breaks at all
Maybe this will earn you some time.
<?php
libxml_use_internal_errors(true); //crazy o tags
$html = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
$dom = new DOMDocument;
$dom->loadHTML($html);
$result='';
foreach ($dom->getElementsByTagName('p') as $node) {
if (strstr($node->nodeValue, 'Legal Disclaimer:')){
break;
}
$result .= $node->nodeValue;
}
echo $result;
This example should successfully store text from html into an array of strings.
After stripping all the tags, you can use preg_split with \R special character ( matches any newline sequence ) to convert string into array. That array will now have several blank values, and there will be also some amount of html non-breaking space entities, so we will check the array for empty values with array_filter() function ( it will remove all items that do not satisfy the filter conditions, in our case, an empty value ). Here are a problem with entity, because and space characters are not the same, they have different ASCII code, so trim() function will not remove spaces. Here are two possible solutions, the first uncommented part will only replace   and check for white space characters, while the second commented one will decode all html entities and also check for spaces.
PHP:
$text = file_get_contents( 'http://pastebin.com/raw.php?i=2Zgbs7hi' );
$text = strip_tags( $text );
$array = array_filter(
preg_split( '/\R/', $text ),
function( &$item ) {
$item = str_replace( ' ', ' ', $item );
return trim( $item );
// $item = html_entity_decode( $item );
// return trim( str_replace( "\xC2\xA0", ' ', $item ) );
}
);
foreach( $array as $value ) {
echo $value . '<br />';
}
Array output:
Array
(
[8] => Hi,
[11] => Ashley has explained that I need to ask for another line and broadband for the wifi to work, please can you arrange this.
[13] => Regards
[23] => Legal Disclaimer:
[24] => This email and its attachments are confidential. If you received it by mistake, please don’t share it. Let us know and then delete it. Its content does not necessarily represent the views of The Dragon Enterprise
[25] => Centre and we cannot guarantee the information it contains is complete. All emails are monitored and may be seen by another member of The Dragon Enterprise Centre's staff for internal use
)
Now you should have clear array with only items with value in it. By the way, newlines in HTML are expressed through <br />, not through \n, your example as response in a web browser still has them, but they are only visible in page source code. I hope I did not missed the point of the question.
try this get text output with line brakes
<?php
$ticket["summary"] = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
$TicketSummaryDisplay = nl2br($ticket["summary"]);
echo strip_tags($TicketSummaryDisplay,'<br>');
?>
You are asking on how to add line-breaks to your "one big block of text with no line breaks at all".
Short answer
After you stripped the HTML tags, apply wordwrap with a desired text-block length
$text = wordwrap($text, 90, "<br />\n");
I really wonder, why nobody suggested that function before.
there is also chunk_split around, which doesn't take words into account and just splits after a certain number of chars. breaking words - but that's not what you want, i guess.
PHP
<?php
$text = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
/**
* Returns string without html tags, also
* removes takes control chars, spaces and " " into account.
*/
function dropHtmlTags($string) {
// remove html tags
//$string = preg_replace ('/<[^>]*>/', ' ', $string);
$string = strip_tags($string);
// control characters and " "
$string = str_replace("\r", '', $string); // remove
$string = str_replace("\n", ' ', $string); // replace with space
$string = str_replace("\t", ' ', $string); // replace with space
$string = str_replace(" ", ' ', $string);
// remove multiple spaces
$string = preg_replace('/ {2,}/', ' ', $string);
$string = trim($string);
return $string;
}
$text = dropHtmlTags($text);
// The Answer: insert line breaks after 95 chars,
// to get rid of the "one big block of text with no line breaks at all"
$text = wordwrap($text, 95, "<br />\n");
// if you want to insert line-breaks before the legal disclaimer,
// uncomment the next line
//$text = str_replace("Regards Legal Disclaimer", "<br /><br />Regards Legal Disclaimer", $text);
echo $text;
?>
Result
first section shows your text block
second section shows the text with wordwrap applied (code from above)
Hello it can be done as follows:
$abc= file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
$abc = strip_tags("\n", $abc);
echo $abc;
Please, let me know whether it works
you may use
<?php
$a= file_get_contents('a.txt');
echo nl2br(htmlspecialchars($a));
?>
<?php
$handle = #fopen("pastebin.html", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgetss($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
output is
Hi,
Ashley has explained that I need to ask for another line and broadband for the wifi to work, please can you arrange this.
Regards
Legal Disclaimer:
This email and its attachments are confidential. If you received it by mistake, please don’t share it. Let us know and then delete it. Its content does not necessarily represent the views of The Dragon Enterprise
Centre and we cannot guarantee the information it contains is complete. All emails are monitored and may be seen by another member of The Dragon Enterprise Centre's staff for internal use
You can probably write additional code to convert to spaces etc.
I'm not sure I did understand everything correctly but this seems to be your expected result:
$txt = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
var_dump(preg_replace("/(\ \;(\s{1,})?)+/", "\n", trim(strip_tags(preg_replace("/(\s){1,}/", " ", $txt)))));
//more readable
$txt = preg_replace("/(\s){1,}/", " ", $txt);
$txt = trim(strip_tags($txt));
$txt = preg_replace("/(\ \;(\s{1,})?)+/", "\n", $txt);
The strip_tags() function strips HTML and PHP tags from a string, if that is what you are trying to accomplish.
Examples from the docs:
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> Other text';
echo strip_tags($text);
echo "\n";
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>
The above example will output:
Test paragraph. Other text
<p>Test paragraph.</p> Other text
here is what i want to do
i am working with php explode function trying to limit characters it prints after defined condition
{
$result=http://php.net
new line characters i don't want to print
$links =explode("://",$result);
$nows=$links[1];
echo $nows;
}
as you can see the above code will print
php.net
new line characters i don't want to print
but instead i want to stop printing after
php.net
You can replace newline characters with nothing:
$nows = str_replace("\n", "", $links[1]);
$nows = str_replace("\r", "", $nows);
echo $nows;
If you want only what is printed on the first line, try this:
$result = "php.net
and some other text";
$nows = reset(explode("\n", str_replace("\r\n", "\n", $result)));
If the part you're looking after will always be in the first line:
$result="http://php.net
new line characters i don't want to print";
$links = explode("\n",$result);
/*
$links[0] ->http://php.net
$links[1] ->new line characters i don't want to print
*/
$links =explode("://",$links[0]);
$nows=$links[1];
echo $nows;
/*
php.net
*/
Anyway , Consider giving more details about your case in order to offer a better way.
For instance , maybe regex?
Try
$nows = trim( $links[1] );
TRIM() will remove newlines among other things
Manual page
EDIT:
Well now we have the actual situation which you say is :-
$result=http://php.net</br>nameserver:ns1</br>nameserver:ns2.
Try
$t = explode( '</br>', $result );
$t1 = explode ( '://', $t[0] );
echo $t1[1];
Just as a note, if it is you that is creating this string somewhere else </br> is not a valid html tag, it should be <br> or if you are using XHTML it should be <br />.
$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']);
?>
I get text via api and sometimes the text can be like so:
hello
world!
How are you?
But I do need the text to be like this:
hello world! How are you?
How to do that?
you can replace the newlines in the text by doing:
$newmsg = str_replace("\n",' ',$yourmsg);
Here is the link to the php function documentation:
http://php.net/manual/en/function.str-replace.php
EDIT: I added a space in the code so it does "hello world..." instead of "helloworld"
Use
$str=" test
hello
world" ;
str_replace ( "\n"," " , $str
) ;
If you want number of replaced count pass the fourth argument
str_replace ( "\n"," " , $str , $count ) ;
$str=<<<EOF
hello
world!
How are you?
EOF;
$s = explode("\n",$str);
print_r(implode(" ",$s));
Here is a really ridiculous solution that I would probably use (bear in mind, ocdcoder's answer works just fine), to make sure I accounted for all possible line endings:
$line_ends = array("\r\n", "\r", "\n"); //notice the order is important.
$new_msg = str_replace($line_ends, " ", $orig_msg);
This way, if there are double line ends, it gets rid of them, but if not, it goes back and checks for single line endings.
But if you want to get more complicated, you could replace your possible carriage-returns with line-ends:
$msg_newline_fix = str_replace("\r", "\n", $orig_message);
$msg_double_newline_fix = str_replace("\n\n", "\n", $msg_newline_fix);
$newmsg = str_replace("\n", " ", $msg_double_newline_fix);
But again, I'm a bit wacky like that. Another crazy solution might be:
$msg_newline_fix = str_replace("\r", "\n", $orig_message);
$msg_array_lines = explode("\n", $msg_newline_fix);
foreach($msg_array_lines as $msg_line){
$clean_line = rtrim($msg_line);
if($clean_line !== '') {
$msg_clean_array[] = $clean_line;
}
}
$new_msg = implode(" ", $msg_clean_array);
But if you know your line endings will be new lines (\n) and not carriage returns (\r) then you are probably safe with a simple one line str_replace.
Finally, you might actually want to preserve line endings when it indicates a new paragraph, something like:
Hello
World!
This is a
new paragraph.
In which case, I would suggest normalizing the line-endings first (making it consistently the same thing so we aren't guessing) and then replacing those empty lines with some kind of safe token you can go back and replace with your new line. Something like:
$msg_carriage_fix = str_replace("\r", "\n\n", $orig_message);
$msg_double_carriage_fix = str_replace("\n\n\n", "\n\n", $msg_newline_fix);
Now we are at the point where we know each line, including empty lines, have only one \n at the end. By replacing the potential \r with two \n, and then replacing only three \n in a row with two \n we avoid the risk of removing any line endings if there were no carriage-return \rs in the first place. Then we can finally do:
$msg_hold_true_linebreaks = str_replace("\n\n", "%line-break%", $msg_double_carriage_fix);
$msg_strip_new_lines = str_replace("\n"," ",$msg_hold_true_linebreaks);
and last but not least:
$new_msg = str_replace("%line-break%","\n",$msg_strip_new_lines);
But,that is only if you really want to keep those true line-breaks and if you want to be extra sure you are ready for carriage-returns, line-ends, and the dreaded \r\n.
I would show yet another version that may shorter and involves using implode and explode, but I'm sure that's enough for now.
edit
Here is a slightly simpler version of that last suggestion, which tries to account for both line endings and intentional line breaks:
$msg_rn_fix = str_replace("\r\n", "\n", $orig_msg);
$msg_r_fix = str_replace("\r", "\n", $msg_rn_fix);
We now know each line ends with a single \n, including empty lines...
$msg_array = explode("\n", $msg_r_fix);
Normal lines each get an array value, but we also know that if the array value is nothing, that it was an intentional hard return...
foreach($msg_array as $msg_line) {
$clean_msg_lines[] = ($msg_line == '') ? "\n" : $msg_line;
}
then we put it all back together:
$new_msg = implode(" ", $clean_msg_lines);
The only flaw is that there will be an extra space before and after each line end. This is easily fixed:
$new_msg = str_replace(" \n ", "\n", $new_msg);
I like this last solution so much, I'm going to copy it below without commentary.
My favorite version
$msg_rn_fix = str_replace("\r\n", "\n", $orig_msg);
$msg_r_fix = str_replace("\r", "\n", $msg_rn_fix);
$msg_array = explode("\n", $msg_r_fix);
foreach($msg_array as $msg_line) {
$clean_msg_lines[] = ($msg_line == '') ? "\n" : $msg_line;
}
$new_msg = implode(" ", $clean_msg_lines);
$new_msg = str_replace(" \n ", "\n", $new_msg);