Script to remove whitespace and list items - php

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.

Related

While retreiving lines from text area in php except for the last element remaining all elements adding space a end

Hi friends when am getting lines from text area and print them in for loop except last element all elements are adding spaces dont know why the space is added as I didnot add any space
Here is code
<form method="post" enctype="multipart/form-data" action="">
<textarea name="words" id="words" rows="10" cols="100"></textarea><br><br>
<input type="submit" name="words_submit" value="Submit keywords">
</form>
<?php
if(isset($_POST['words_submit']))
{
$text = trim($_POST['words']);
$text = explode ("\n", $text);
foreach ($text as $line) {
for($i=0; $i<4; $i++){
echo $line;
}
}
}
?>
suppose if 2 items in text area are hello,welcome then it showing output as
hello hello hello hello welcomewelcomewelcomewelcome
why there are spaces between hello can anyone please help me with this
Remove the \r characters as well during the explode step.
if (isset($_POST['words_submit'], $_POST['words'])) {
$text = explode ("\r\n", trim($_POST['words']));
foreach ($text as $line) {
echo str_repeat($line, 4);
}
}
This assumes the unrendered text is hello\r\nwelcome.
In your code, $text is holding hello\r and welcome.
The \r is rendered as a whitespace character.
you can use rtrim() to get rid off spaces
foreach ($text as $line) {
for($i=0; $i<3; $i++){
echo rtrim($line,' ');
}
}
Hope it helps

convert string fetched with php nl2dr into array [duplicate]

I have form in html where user can put the text in text area.
I save the content of text area into MySQL database (in field of type TEXT).
Then I somewhere in my aplication I need load that text and put it into array where in each index will be one line of the text.
<textarea rows="10" cols="80">
Row one
Row two
Row tree
</textarea>
array (output in "php pseudocode"):
$array = array();
$array[0] = Row one;
$array[1] = Row two;
$array[2] = Row tree;
How I do it:
I save it to db then I load it and use:
$br = nl2br($string,true);
$array = explode("<br />", $br);
The reason why I use nl2br is I want to avoid problems with end of lines of the text from different platforms. I mean /n or /r/n.
But in my solution must be an error somewhere cause it doesn't work (an array $array is empty).
Better solution would be probably somehow split it into array using explode or something like that with pattern for line breaks but here is again the problem from beginning with line breaks which I don't know how to solve (problems with \n or \r\n).
Can anybody give me an advice? Thanks.
I'd suggest you skip the nl2br until you're ready to actually send the data to the client. To tackle your problem:
// $string = $get->data->somehow();
$array = preg_split('/\n|\r\n/', $string);
When you receive the input in your script normalize the end-of-line characters to PHP_EOL before storing the data in the data base. This tested out correctly for me. It's just one more step in the "filter input" process. You may find other EOL character strings, but these are the most common.
<?php // RAY_temp_user109.php
error_reporting(E_ALL);
if (!empty($_POST['t']))
{
// NORMALIZE THE END-OF-LINE CHARACTERS
$t = str_replace("\r\n", PHP_EOL, $_POST['t']);
$t = str_replace("\r", PHP_EOL, $t);
$t = str_replace("\n", PHP_EOL, $t);
$a = explode(PHP_EOL, $t);
print_r($a);
}
$form = <<<FORM
<form method="post">
<textarea name="t"></textarea>
<input type="submit" />
</form>
FORM;
echo $form;
Explode on PHP_EOL and skip the nol2br() part. You can use var_dump() to see the resulting array.

Insert a Break after every 55 characters

I want to insert a line Break after every 55 characters i have made a jquery script but it doesn't work can some one please point me in the right direction
Jquery.js
$(document).ready(function() {
$('#text_comment').text($(this).val().replace(/([\s\S]{55})/g, '$1<br />'));
});
Index.php
<input type="text" class="comment" id="text_comment"autocomplete="off"time_date="<?php echo $date_shared;?>"
username="<?php echo $comment_username;?>"post_id="<?php echo $shared_id2; ?>"placeholder="Write a Comment"/>
Line-breaks are automatically removed from inputs with a type of text.
text: A single-line text field; line-breaks are automatically removed from the input value.
You can use a textarea to display the line breaks:
var myString = '1234567890';
myString = myString.replace(/.{1,2}/g, "$&\n"); //replace 2 with 55 for your example
document.getElementById('text').value = myString; // :(
document.getElementById('textarea').value = myString; // :)
<input type="text" id="text"> <-- line-breaks automatically removed
<br>
<textarea id="textarea" rows="7"></textarea>
You can use this approach.
$original = "Sample String.";
$parts = str_split($original, 4); //Replace '4' with '55' afterwards.
$final = implode("<br />", $parts);

PHP add param at the beginning and end of every line from textarea

Im not familiar with PHP too much and I need to make a function that will read and add some string to every line from my textarea.
Example textarea
AAA
BBB
CCC
And what I need is
somestringAAAotherstring
somestringBBBotherstring
somestringCCCotherstring
and show it as output after sending "post".
EDIT:
My form is
<FORM METHOD ="POST">
<textarea rows="30" name="content"></textarea>
<INPUT TYPE = "Submit" VALUE = "Send">
</FORM>
and yes, question is "how to do it?"
$text = trim($_POST['textareaname']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $lines) {
$line = $sometext . $lines . $someOtherText;
//proceed furthur
}

Handling new lines in php

I have form in html where user can put the text in text area.
I save the content of text area into MySQL database (in field of type TEXT).
Then I somewhere in my aplication I need load that text and put it into array where in each index will be one line of the text.
<textarea rows="10" cols="80">
Row one
Row two
Row tree
</textarea>
array (output in "php pseudocode"):
$array = array();
$array[0] = Row one;
$array[1] = Row two;
$array[2] = Row tree;
How I do it:
I save it to db then I load it and use:
$br = nl2br($string,true);
$array = explode("<br />", $br);
The reason why I use nl2br is I want to avoid problems with end of lines of the text from different platforms. I mean /n or /r/n.
But in my solution must be an error somewhere cause it doesn't work (an array $array is empty).
Better solution would be probably somehow split it into array using explode or something like that with pattern for line breaks but here is again the problem from beginning with line breaks which I don't know how to solve (problems with \n or \r\n).
Can anybody give me an advice? Thanks.
I'd suggest you skip the nl2br until you're ready to actually send the data to the client. To tackle your problem:
// $string = $get->data->somehow();
$array = preg_split('/\n|\r\n/', $string);
When you receive the input in your script normalize the end-of-line characters to PHP_EOL before storing the data in the data base. This tested out correctly for me. It's just one more step in the "filter input" process. You may find other EOL character strings, but these are the most common.
<?php // RAY_temp_user109.php
error_reporting(E_ALL);
if (!empty($_POST['t']))
{
// NORMALIZE THE END-OF-LINE CHARACTERS
$t = str_replace("\r\n", PHP_EOL, $_POST['t']);
$t = str_replace("\r", PHP_EOL, $t);
$t = str_replace("\n", PHP_EOL, $t);
$a = explode(PHP_EOL, $t);
print_r($a);
}
$form = <<<FORM
<form method="post">
<textarea name="t"></textarea>
<input type="submit" />
</form>
FORM;
echo $form;
Explode on PHP_EOL and skip the nol2br() part. You can use var_dump() to see the resulting array.

Categories