I'm working on a simple script that get's a txt file posted to it and then displays the file contents. However, I'm having issues preserving line breaks.
It's being saved with windows notepad, which I think adds the CR LF for each line break, and then uploaded through a PHP form. I can echo the whole file contents but I need a way to split the data into new lines.
I've already tried to do echo str_replace(array("\r\n", "\r", "\n"), '<br />', $file); and nl2br($file). Neither worked.
I'm opening the file with `file_get_contents($_FILES['file']['tmp_name'])'
Thanks.
Have you considered reading the file into an array using the file() function in PHP?
http://php.net/manual/en/function.file.php
Then you can output as needed, but each line will be in a single element of the array.
What works faster for me is to copy paste any text or Excel or HTML table type or newline type of data and paste it into a textarea instead of an inputextbox:
<textarea id="txtArea" name="txtArea" rows="40" cols="170"></textarea>
<br>
<input type="submit" value="split lines into array" />
in the form receiving file:
$txtArea ='';
$txtArea = $_POST['txtArea'];
$TA = $_POST['txtArea'];
$string = $TA;
$array = preg_split ('/$\R?^/m', $string);
// or any of these:
// $array = explode(PHP_EOL,$string);
// $array = explode("\n", $txtArea);
echo "<br>A0: ".$array[0];
echo "<br>A1: ".#$array[1];
echo "<br>A2: ".#$array[2];
Related
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.
I am trying to read a .tsv file using PHP. I am using the simplest method of file_get_contents() but it is skipping any text between <> tags.
Following is the format of my .tsv file
<id_svyx35_88c_avbfa5> <Kuldeep_Raval> rdf:type <wikicat_Delhi_Daredevils_cricketers>
Following is the code I am using
$filename = "access_s.tsv";
$content = file_get_contents($filename);
//Split file into lines
$lines = explode("\n", $content);
echo $content;
On reading it, the output is just
rdf:type
Please help in what can be the solution to read the line as it is?
Try to apply htmlspecialchars() to $content:
$filename = "access_s.tsv";
$content = htmlspecialchars(file_get_contents($filename));
//Split file into lines
$lines = explode("\n", $content);
echo $content;
Reference on php.net
The tags have always been there, the browser just does not show them. Just like with any valid HTML tag, you can see them when viewing the source code of the website.
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.
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.
I've learned it's possible to trim a string from a textarea and put break tags after it, so each sentence written at a new line in the textbox will also be written at a new line in the PHP file.
This is the snippet:
<html>
<body>
<?php
$text = trim($_POST['textarea']);
$text = nl2br($text);
echo $text;
?>
</body>
</html>
The thing is that my true intentions are:
Use the contents of each line in the textbox for a certain script
Print the contents of each line with the results from the script added all separated by lines.
<?php
$text = trim($_POST['textarea']);
$text = explode ("\n", $text);
foreach ($text as $line) {
echo myFunction($line);
echo "< hr />";
}
?>
The PHP function explode lets you take a string and blow it up into smaller pieces. Store this array for use in other scripts
$str_arr = explode("\n", $_POST['textarea']);
//$str_arr can be used for other script