How can I detect that there is different paragraphs in a form? In this example if the user writes different paragraphs, the echo puts all toguether. I tried white-space:pre and it did not work. I do not know what else can I do to echo the text with <p>?
CSS:
#text {
white-space:pre;
}
HTML:
<form action='normal-html.php' method='post'>
<textarea id="text" name='text' rows='15' cols='60'></textarea> <br/>
<input type='submit' value='Convertir a html' />
</form>
<br />
<?php
$text = $_POST[text];
echo $text;
?>
This sounds like a job for http://php.net/manual/en/function.nl2br.php
string nl2br ( string $string [, bool $is_xhtml = true ] )
Returns string with '<br />' or '<br>' inserted before all
newlines (\r\n, \n\r, \n and \r).
You can use this as you echo out the data, so that way you are never changing what is in the database - or you can simply alter the user input as you save it to the database. Personally I am a fan of the first option, but whatever works best for your application.
Edit: If you want to use only <p> tags, you could also do this using str_replace:
$text = '<p>';
$text.= str_replace('\n', '</p><p>', $_POST[text]);
The \n is generally a new line, depending on how it is read, you may need to use \r\n and the string replace will do the rest. This will leave a spare <p> on the end of the string, but you see where this is going.
You can use the explode function (php manual page):
$your_array = explode("\n", $your_string_from_db);
Example:
$str = "Lorem Ipsum\nAlle jacta est2\nblblbalbalbal";
$arr = explode("\n", $str);
foreach ( $arr as $item){
echo "<p>".$item."</p>";
}
Output:
Lorem Ipsum
Alle jacta est
blblbalbalbal
Related
Wanted to convert
<br/>
<br/>
<br/>
<br/>
<br/>
into
<br/>
You can do this with a regular expression:
preg_replace("/(<br\s*\/?>\s*)+/", "<br/>", $input);
This if you pass in your source HTML, this will return a string with a single <br/> replacing every run of them.
Mine is almost exactly the same as levik's (+1), just accounting for some different br formatting:
preg_replace('/(<br[^>]*>\s*){2,}/', '<br/>', $sInput);
Enhanced readability, shorter, produces correct output regardless of attributes:
preg_replace('{(<br[^>]*>\s*)+}', '<br/>', $input);
Thanks all..
Used Jakemcgraw's (+1) version
Just added the case insensative option..
{(<br[^>]*>\s*)+}i
Great tool to test those Regular expressions is:
http://www.spaweditor.com/scripts/regex/index.php
without preg_replace, but works only in PHP 5.0.0+
$a = '<br /><br /><br /><br /><br />';
while(($a = str_ireplace('<br /><br />', '<br />', $a, $count)) && $count > 0)
{}
// $a becomes '<br />'
Use a regular expression to match <br/> one or more times, then use preg_replace (or similar) to replace with <br/> such as levik's reply.
You probably want to use a Regular Expression. I haven't tested the following, but I believe it's right.
$text = preg_replace( "/(<br\s?\/?>)+/i","<br />", $text );
A fast, non regular-expression approach:
while(strstr($input, "<br/><br/>"))
{
$input = str_replace("<br/><br/>", "<br/>", $input);
}
User may enter many variants
<br>
<br/>
< br />
<br >
<BR>
<BR>< br>
...and more.
So I think it will be better next
$str = preg_replace('/(<[^>]*?br[^>]*?>\s*){2,}/i', '<br>', $str);
I am trying to do a line break after the message "Original message", I have tried with this but It keeps showing me the
---Original message---<br />
message
<textarea id="txtMessage" rows="10" cols="50"><?php echo nl2br(str_replace('<br/>', " ","---Original message---\n".$array['message']));?></textarea>
I want something likes this:
---Original message---
message
any advise?
This should do what you want it to:
<?php echo str_replace('<br />', " ","---Original message---\n".$array['message']);?>
nl2br — Inserts HTML line breaks before all newlines in a string (from php.net)
Example:
echo "<textarea>HI! \nThis is some String, \nit works fine</textarea>";
Result:
But if you try this:
echo nl2br("<textarea>HI! \nThis is some String, \nit works fine</textarea>");
you will get this:
Therefore you should not use nl2br before saving it to database, otherwise you have to get rid of <br /> every time you try to edit text! Just use it when you print it out as text.
echo nl2br(str_replace('<br/>', " ", ... ));
should be
echo str_replace('<br />', ' ', ... );
The php function "nl2br" takes newlines, and converts them into br tags. If you don't want that, you should probably remove it :).
Heh, beaten by Ryan.
You're trying to replace <br/>, but the original text has <br /> (note the space).
You are removing the HTML breaks, then adding them back! Look at your code:
nl2br(str_replace('<br/>', " ","---Original message---\n".$array['message']))
First, str_replace replaces '<br/>' with a space. Then, nl2br adds a <br> for every newline (\n) it finds.
Remove nl2br call and it's done.
If you want to do nl2br on all of the text except for what's inside the textarea you could do this:
function clean_textarea_of_br($data) {
return str_replace(array("<br>", "<br/>", "<br />"), "", $data[0]);
}
$message = preg_replace_callback('#<textarea[^>]*>(.*?)</textarea>#is',clean_textarea_of_br,$message);
I'm trying to use preg_replace to strip out a section of code but I am having problems getting it to work right.
Code Example:
$str = '<p class="code">some string here</p>';
PHP I'm using:
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
preg_replace($pattern,"", $str);
This strips out the code just as I want with the exception of the space between the p and class.
Returns:
some string here //notice the single space at the beginning.
I'm trying to get:
some string here //no space at the beginning.
I have been beating my head against the wall trying to find a solution. The reason I'm trying to strip it out in a chunk instead of breaking the preg_replace into pieces is because I don't want to change anything that may be in the string between the tags. Any ideas?
That does not happen for me (and it shouldn't).
It may be a space output somewhere else (use var_dump() to view the string).
You might want to look into this thread to see if you want to switch to using DOMDocument. It'll save you a great deal of headaches trying to parse through HTML.
Robust and Mature HTML Parser for PHP
test:
<?php
$str = '<p class="code">some string here</p>';
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
$result = preg_replace($pattern,"", $str);
var_dump($result);
result:
php pregrep.php
string(16) "some string here"
seems to work just fine.
Alex I figured out where I was picking up the extra space.
I was putting that code into a text area like this:
$str = '<p class="code">some string here</p>';
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
$strip_str = preg_replace($pattern,"", $str);
<textarea id="code_area" class="syntaxhl" name="code" cols="66" rows="5">
<?php echo $strip_str; ?>
</textarea>
This gave me my extra space but when I changed the code to:
<textarea id="code_area" class="syntaxhl" name="code" cols="66" rows="5"><?php echo $strip_str; ?></textarea>
No line spaces or breaks the extra space went away.
Why not use trim()?
$text = trim($text);
This removes white spaces around strings.
I am creating a format tool that strips content from articles for print. The demo can be seen here. The full source is avaliable here.
Right now the tool strips formating and can also keep paragraphs by using nl2br What I would like to do is to be able to shift the content to the left and only have a paragraph if there is a break between the content.
for example:
This
is
the
first
paragraph
Second Paragraph
Becomes:
this is the first paragraph
Second Paragraph
I tried this by using regex to check if there were two spaces at the end but that didn't work. Here is some sample code:
HTML:
<form method="post" action="">
<textarea cols="68" rows="21" name="textinput"></textarea><br/>
<input type="checkbox" name="keep_paragraphs" value="true" checked /> Keep Paragraphs<br/>
<input type="checkbox" name="shift_left" value="true" /> Remove whitespace after line unless it ends in two spaces<br/>
<input type="submit" value="Submit" />
</form>
PHP:
$text= $_POST['textinput'];
$p= $_POST['keep_paragraphs'];
$lb= $_POST['shift_left'];
if(get_magic_quotes_gpc()){
$text = stripslashes($text);
// strip off the slashes if they are magically added.
}
$text = htmlentities($text);
//if we should keep formatting
if($p=="true"){
$text =nl2br($text);
}
if($lb=="true"){
$text = preg_replace('/\s+/', ' ', trim($text));
}
echo $text;
Any help on this would be great
EDIT: include example
POST textbox = "Hi Jane
How are You doing today
I hope all is well";
Most text will be coming from e-mails and other sources,basicly it needs to be super genderic.
The regex you need is,
/(?<!\r\n)\r\n(?=\w)/
replace it with a space.
Update
A small correction,
$text ="This
is
a
paragraph
Second Paragraph";
$lb = "true";
if($lb=="true"){
$text2 = preg_replace('/(?<!\r\n)\r\n(?=\w)/', ' ', trim($text));
}
echo $text2;
Your can write this
$text = preg_replace('#\n([a-z])#Us', ' \1', trim($text));
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);