I tried PHP explod() built-in function to explod my text data stored in a mysql database.
here is I tried sample PHP code:
// Get mysql database data(with \n).
$str_in =
'one
two
three
fore
five
six
';
// Convert \n into <br>.
$str = nl2br($str_in);
// Explode $str and wrapped into <p> tags.
$str_exploded = explode("<br><br>",$str);
foreach($str_exploded as $sub_str) {
echo '<p>'.$sub_str.'</p>';
}
Then I got this output.
<p>one<br>
two<br>
three<br>
<br>
fore<br>
five<br>
<br>
six<br>
</p>
but this is not what I'm expected. I want somthing like this.
<p>one<br>
two<br>
three</p>
<p>fore<br>
five</p>
<p>six</p>
how can I achive this? thanks.
What you are trying to do is remove a when its the only thing on the line.
Strreplace should work with the argument "\n" and a replacement of "\n"
You incorrectly presume, that nl2br function replaces "\n" with <br>. In reality it inserts <br /> before the \n. So, \n\n becomes <br />\n<br />\n. Your
explode("<br><br>",$str)
doesn't work as expected.
To fix it I used exploding by \n\n:
Code
<?php
$str_in =
'one
two
three
fore
five
six
';
$str_exploded = preg_split("/(:?\r?\n){2}/",$str_in);
$n = count($str_exploded);
for ($i = 0; $i < $n; ++$i)
{
// Convert \n into <br>.
$str_exploded[$i] = nl2br($str_exploded[$i]);
echo '<p>'.$str_exploded[$i]."</p>";
if ($i !== $n - 1)
{
print "\n\n";
}
}
Output
<p>one<br />
two<br />
three</p>
<p>fore<br />
five</p>
<p>six<br />
</p>
Related
I have a text area that gets input from a PHP script, and I would like to count the number of words or line breaks in the textarea and echo it below the text area.
This is what the code looks like for the textarea.
<textarea name="domains" cols="120" rows="5" style="max-width:100%;">
<?php $output_array = explode(" ",$output);
$count = count($output_array);
for ($i=0;$i<$count;$i++){
echo $output_array[$i]."\n";
}
?>
</textarea><br />
<br>
<?php
preg_match_all("/(\n)/", $_POST['domains'], $matches);
$total_lines = count($matches[0]) + 1;
echo $total_lines;
?>
<br />
I tried using preg_match_all but the output I get is only "1", regardless of how many line breaks are inside the text area.
$str = 'as aa frd sad as
kjhsdf sdkjh
sd sdkjhsdf
sjkldhfh sdfjh sd';
preg_match_all("/\w+/", $str, $matches);
echo 'Words = ' . count($matches[0]);
echo PHP_EOL;
preg_match_all("/\n/", $str, $matches);
echo 'newlines = ' . count($matches[0]);
echo PHP_EOL;
echo 'So number of line is = ' . count($matches[0])+1;
RESULT
Words = 12
newlines = 3
So number of line is = 4
You can do the following:
$arr = array_filter(explode(" ", $input) function($item) {
return !!$item;
});
$count = count($arr) + count(explode("\n", implode(",", $arr)));
This splits the string by space, filters out empty items to avoid issues due to multiple spaces found between words, then glues the array back into a string, splits it by newline and adds the two counts together.
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.
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
<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);