Is it possible to replace newlines with the <br> tag, but to ignore newlines that follow a </h1> tag?
So for example I want to change this block:
<h1>Test</h1> \n some test here \n and here
To this:
<h1>Test</h1> some test here <br /> and here
$subject = "<h1>hithere</h1>\nbut this other\nnewline should be replaced.";
$new = preg_replace("/(?<!h1\>)\n/","<br/>",$subject);
echo $new;
// results in:
// <h1>hithere</h1>
// but this other<br/>newline should be replaced.
Should work. This says \n not preceeded immediately by h1>
Using string functions instead of regular expressions, and assuming the </h1> tag can be anywhere on the line (instead of just before the newline):
$lines=file($fn);
foreach ($lines as $line) {
if (stristr("$line", "</h1>") == FALSE) {
$line = str_replace("\n", "<br />", $line);
}
echo $line;
}
which, for your example, results in:
<h1>Test</h1>
some test here <br />and here<br />
Related
Why is the following code not working...?
$test = "hello \n world \n !";
foreach(explode("\n",$test) as $line){
echo $line;
}
It prints
hello world !
Instead of
hello
world
!
Thanks
You also have to echo <br />
The HTML <br /> element produces a line break in text (carriage-return).
It is useful for writing a poem or an address, where the division of
lines is significant.
$test = "hello \n world \n !";
foreach(explode("\n",$test) as $line){
echo $line;
echo "<br />";
}
doc: <br />
Another option is to use nl2br to inserts HTML line breaks before all newlines in a string
$test = "hello \n world \n !";
echo nl2br($test);
Doc: nl2br()
Add new line to Browser Output via HTML
In HTML, you need to add line break for new line via HTML Tag. This will not appear as required output if there is line break in text/string.
<br> used to add single line break.
Replace
echo $line;
Into
echo $line."<br>";
Add new line to string/source code
If you need to add new line into source code only then replace echo $line; with echo $line."\n";
\n is used into double quotes for new line.
Add new line to Browser Output via PHP
Anyways an other way to do this via PHP is to use PHP's built-in method nl2br()
$test = "hello \n world \n !";
foreach(explode("\n",$test) as $line){
echo $line;
}
The result is:
hello world !
Basically you have split on the newlines, and the newlines are not included as you print out each split part.
Use nl2br($line) and replace the delimiter with empty space.This way your new line will be visible in html:
$test = "hello \n world \n !";
foreach(explode(" ",$test) as $line){
echo nl2br($line);
}
will output:
hello
world
!
and the output html:
hello<br />
world<br />
!
I'm trying to append <br/> to all lines that do not end with an html tag, but I'm unable to get it working.
I've got this so far, but it seems to match nothing at all (in PHP).
$message=preg_replace("/^(.*[^>])([\n\r])$/","\${1}<br/>\${2}",$message);
Any ideas on how to get this working properly?
I think you need the m modifier on your regex:
$message=preg_replace("/^(.*[^>])$/m", "$1<br/>\n", $message);
// ^
// Here
m makes ^ and $ match start/end of lines in addition to start/end of string.
No [\n\r] needed.
Also, why do you want to match all the line to just put it back after ?
It is actually as simple as
$message = preg_replace ('/([^>])$/m', '$1<br />', $message);
Example code:
<?php
$message = "<strong>Hey</strong>
you,
No you don't have to go !";
$output = preg_replace ('/([^>])$/m', '$1<br />', $message);
echo '<pre>' . htmlentities($output) . '</pre>';
?>
You can use this:
$message = preg_replace('~(?<![\h>])\h*\R~', '<br/>', $message);
where:
`\h` is for horizontal white spaces (space and tab)
`\R` is for newline
(?<!..) is a negative lookbehind (not preceded by ..)
I've found this that works somehow, see http://phpfiddle.org/main/code/259-vvp:
<?php
//
$message0 = "You are OK.
<p>You are good,</p>
You are the universe.
<strong>Go to school</strong>
This is the end.
";
//
if(preg_match("/^WIN/i", PHP_OS))
{
$message = preg_replace('#(?<!\w>)[\r]$#m', '<br />', $message0);
}
else
{
$message = preg_replace('#(?<!\w>)$#m', '<br />', $message0);
}
echo "<textarea style=\"width: 700px; height: 90px;\">";
echo($message);
echo "</textarea>";
//
?>
Gives:
You are OK.<br />
<p>You are good,</p>
You are the universe.<br />
<strong>Go to school</strong>
This is the end.<br /><br />
Add a < br /> if not ended up with a HTML tag like:
< /p>, < /strong>, ...
Explanation:
(?<!\w>): negative lookbehind, if a newline character is not preceded
by a partial html close tag, \w word character + closing >, like a>, 1> for h1>, ...
[\r\n]*$: end by any newline character or not.
m: modifier for multiline mode.
I use nl2br when displaying some information that is saved somewhere, but when HTML tags are used I want not to add <br> tags for them.
For example if I use
<table>
<th></th>
</table>
it will be transformed to
<table><br />
<th></th><br />
</table><br />
and that makes a lot of spaces for this table.
Ho can break line tags be added only for other non-HTML content?
Thanks.
I'd the same issue,
I made this code, adding a <br /> at the end of each line except if the line finished with an html tag:
function nl2br_save_html($string)
{
if(! preg_match("#</.*>#", $string)) // avoid looping if no tags in the string.
return nl2br($string);
$string = str_replace(array("\r\n", "\r", "\n"), "\n", $string);
$lines=explode("\n", $string);
$output='';
foreach($lines as $line)
{
$line = rtrim($line);
if(! preg_match("#</?[^/<>]*>$#", $line)) // See if the line finished with has an html opening or closing tag
$line .= '<br />';
$output .= $line . "\n";
}
return $output;
}
You could replace the closing tags and newlines by only closing tags:
$str = str_replace('>
', '>', $str);
I think your question is wrong. If you are typing
<table>
<th></th>
</table>
into a text area then no matter what you do It will include <br /> in between them. Because it is what nl2br is supposed to do.
<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
I need to strip all <br /> and all 'quotes' (") and all 'ands' (&) and replace them with a space only ...
How can I do this? (in PHP)
I have tried this for the <br />:
$description = preg_replace('<br />', '', $description);
But it returned <> in place of every <br />...
Thanks
<?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>');
?>
http://php.net/manual/en/function.strip-tags.php
You can use str_replace like this:
str_replace("<br/>", " ", $orig );
preg_replace etc uses regular expressions and that may not be what you want.
If str_replace() isnt working for you, then something else must be wrong, because
$string = 'A string with <br/> & "double quotes".';
$string = str_replace(array('<br/>', '&', '"'), ' ', $string);
echo $string;
outputs
A string with double quotes .
Please provide an example of your input string and what you expect it to look like after filtering.
To manipulate HTML it is generally a good idea to use a DOM aware tool instead of plain text manipulation tools (think for example what will happen if you enounter variants like <br/>, <br /> with more than one space, or even <br> or <BR/>, which altough illegal are sometimes used). See for example here: http://sourceforge.net/projects/simplehtmldom/
To remove all permutations of br:
<br> <br /> <br/> <br >
check out the user contributed strip_only() function in
http://www.php.net/strip_tags
The "Use the DOM instead of replacing" caveat is always correct, but if the task is really limited to these three characters, this should be o.k.
Try this:
$description = preg_replace('/<br \/>/iU', '', $description);
$string = "Test<br>Test<br />Test<br/>";
$string = preg_replace( "/<br>|\n|<br( ?)\/>/", " ", $string );
echo $string;
This worked for me, to remove <br/> :
(> is recognised whereas > isn't)
$temp2 = str_replace('<','', $temp);
// echo ($temp2);
$temp2 = str_replace('/>','', $temp2);
// echo ($temp2);
$temp2 = str_replace('br','', $temp2);
echo ($temp2);