How to store mulitple data from a textarea in array - php

I have a textarea and a submit button and on click of the button I want that all the data seperated by a new line inserted into an array.
Here is the form file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<form action="export.php" method="POST">
<textarea name="num1" placeholder="Enter Numbers You Want To See records Of....">
</textarea>
<input type="submit" name="sub">
</form>
</body>
</html>
And Here is the PHP file
<?php
include 'connect.php';
$newnum = '';
$a = array($_POST['num1']);
foreach($a as $i=>$checknum) {
$newnum = "'".$checknum."'".',';
}
$newnum = rtrim($newnum,',');
echo "$newnum";
?>
This is what I am expecting:
Input -
1111
222
333
444
55
Output - '1111','222','333','444','55'

$a = "1111\n222\n333\n444\n55";
echo $a . PHP_EOL;
/*
1111
222
333
444
55
*/
// explode("\n", $a) ->
// Explodes input by new line into following array [1111, 222, 333, 444, 55]
// fn($line) => "'$line'" ->
// anonymous function that takes one input and wraps it between ''
// Replace with function($line) {return "'$line'";} if using PHP < 7.4
// array_map ->
// takes a callback function and an array and returns a new array by applying a callback to each item
// implode(',', ...) ->
// join all elements in new array with a separator ','
$newnum = implode(',', array_map(fn($line) => "'$line'", explode("\n", $a)));
echo $newnum;
/*
'1111','222','333','444','55'
*/
Actually you could just implode them with "','" and add ' to both ends.
$newnum = "'" . implode("','", explode("\n", $a)) . "'";

Try
$newnum = '';
$a = explode("\n", $_POST['num1']);
foreach($a as $i=>$checknum) {
$newnum. = "'".$checknum."'".',';
}
$newnum = rtrim($newnum,',');

you can use :
$res = array_filter(array_map(function($value){
return trim($value);
}, explode("\n", $a)));
Even if the person add lot of spaces ou add lot of new lines, the code will work.
Regards

assume input from textarea is:
7
10
55
$textbox_string = '7'.PHP_EOL.'10'.PHP_EOL.'55';
$arr = explode(PHP_EOL, $textbox_string);
$in_nums_query_str = implode(',', $arr);
$in_nums_query_str = str_replace(PHP_EOL, '', $in_nums_query_str);
$in_nums_query_str = str_replace(",", "','", $in_nums_query_str);
$in_nums_query_str = "'" . $in_nums_query_str . "'";
echo $in_nums_query_str;
will echo
'7','10','55'

Related

How to add value into array php file When html form submit in php?

I have one html form as index.php and also another mydata.php file. I want to put data into mydata.php file, but there is some issue
index.php
<form action="" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<?php
if (isset($_POST['field1']) && isset($_POST['field2'])) {
if (!filesize('mydata.php')) {
$data0 = '<?php $a = array(' . "\n";
$ret = file_put_contents('mydata.php', $data0, FILE_APPEND | LOCK_EX);
}
$data = '"' . $_POST['field1'] . '"' . '=>' . '"' . $_POST['field2'] . '",' . "\n";
$ret = file_put_contents('mydata.php', $data, FILE_APPEND | LOCK_EX);
if ($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
}
?>
mydata.php
$array = array("a"=>"b");
When I add submit new value i want to need push new array like my post data
Array
(
[field1] => c
[field2] => d
[submit] => Save Data
)
$array = array("a"=>"b","c"=>"d");
You just need to add data to $array, generate the PHP code and then save it into file.
Example with PHP file:
<?php
// data for the form ($_POST), all data from the client (browser) MUST be validated and sanitized
$formData = [
'field1' => 'c',
'field2' => 'd'
];
// load mydata.php if it was not loaded before
require_once 'mydata.php';
// add new data or update existen
$array = array_merge($array, $formData);
$tab = ' ';
// generate the new content for the mydata.php file
$newContent = '<?php' . PHP_EOL . '$array = [' . PHP_EOL;
foreach ($array as $key => $value)
$newContent .= $tab . "'$key' => '" . addslashes($value) . "'," . PHP_EOL;
$newContent .= '];' . PHP_EOL;
//save the new content into file
file_put_contents('mydata.php', $newContent);
But I really recommend to you use the JSON file for that.
Example with JSON file:
<?php
// data for the form ($_POST), all data from the client (browser) MUST be validated and sanitized
$formData = [
'field2' => 'c',
'field3' => 'd'
];
$array = [];
// load data
if (file_exists('mydata.json'))
$array = json_decode(file_get_contents('mydata.json'), true);
// add new data or update the existen
$array = array_merge($array, $formData);
// save the new data into file
file_put_contents('mydata.json', json_encode($array), LOCK_EX);
I'm not sure what you are asking because the question is not clear, but if I am getting it right, to add add a new key-value pair to your existing array, you could try
$field1 = $_POST['field1']; // $field1 = "c"
$field2 = $_POST['field2']; // $field2 = "d"
$array[$field1] = $field2;

PHP & MYSQL Insert into database with a textarea (new line & new line into database)?

<?php
require 'db2.php';
?>
<html>
<form action="" method="POST">
<textarea rows="5" cols="80" id="proxies" name="proxies">
</textarea>
<input type="submit" name="insert" value="Insert">
</form>
</html>
<?php
if (isset($_POST['insert']))
{
$string = $_POST['proxies'];
$arrray = explode(':',$string);
$proxy = $arrray[0] . ':' . $arrray[1];
$country = $arrray[2];
$state = $arrray[3];
$city = $arrray[4];
$query = mysqli_query($link,"INSERT INTO `proxies`(`proxy`,`country`, `state`, `city`) VALUES ('{$proxy}', '{$country}', '{$state}', '{$city}')");
}
?>
So basically, I'm confused I thought this would add every new line, but obviously I was wrong.
How would I get this text area to submit into my database line per line like e.g.
If I entered this into the text area
test:80:test:test:test
test:80:test:test:test
test:80:test:test:test
test:80:test:test:test
It'll add all of those 4 records, cheers!
use this code :
$text = trim($_POST['textareaname']);
$textAr = explode("\n", $text); // remove the last \n or whitespace character
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
}
for more explanation see this question.
Please try this code:
$string = trim($_POST['proxies']);
$stringArray = explode("\n" , $string);
$stringArray = array_filter($stringArray,'trim');
foreach($stringArray as $ $string){
$arrray = explode(':',$string);
$proxy = $arrray[0] . ':' . $arrray[1];
$country = $arrray[2];
$state = $arrray[3];
$city = $arrray[4];
$query = mysqli_query($link,"INSERT INTO `proxies`(`proxy`,`country`, `state`, `city`) VALUES ('{$proxy}', '{$country}', '{$state}', '{$city}')");
}
I would recommend you to append
PHP_EOL
PHP_EOL - is a End of line constant in PHP, Append that at the end of string instead of '\n'
I hope it will solve the problem,

Php Unexpected T_FOR, expecting ). Creating multi-dimensional arrays using for()

here is my code. What I am trying to achieve is get text like this
Hola Hi
Pollo Chicken
Queso Cheese
and so on, and be able to make an array out of it such that
array[0][1] is Hi.
here is my code, the error is on line 13
<?php
if(isset($_POST['submit'])){
$message = $_POST['text'];
$words2 = explode("\r\n", $message);
$words = explode("\t", $words2[0]);
$numberoflines = count($words2);
echo $numberoflines;
for($i=0; $i<$numberoflines; $i++){
$words[$i] = $line;
$arrayline = explode("\t", $line);
$cow = array(
for($u=0; $u<2; $u++){
array($arrayline[$u])
}
);
}
}
?>
<html>
<form method = "POST" method ="changetext.php">
<textarea name="text">
</textarea>
<input type="submit" value = "Flip!" name="submit">
</form>
</html>
Maybe thats what you wanted to achieve ?!?
for($i=0; $i<$numberoflines; $i++){
$arraycols= explode("\t", $words[$i]);
foreach($arraycols as $col){
$list[$i][] = $col;
}
}
so Array $list is $list[row][col]
if i got right what is inside the $words Array. Your code is a little messi ;)
Try something like this:
$words = array();
if(isset($_POST['submit'])){
// Break down the text as lines:
$lines = explode("\r\n", $_POST['text']);
// For every line...
foreach($lines as $line){
// Seperate the 2 words (seperated by a tab)
$words[] = explode("\t", $line);
}
// Print the result:
var_dump($words);
}

parsing .srt files

1
00:00:00,074 --> 00:00:02,564
Previously on Breaking Bad...
2
00:00:02,663 --> 00:00:04,393
Words...
i need to parse srt files with php and print the all subs in the file with variables.
i couldn't find the right reg exps. when doing this i need to take the id, time and the subtitle variables. and when printing there musn't be no array() s or etc. must print just the same as in the orginal file.
i mean i must print like;
$number <br> (e.g. 1)
$time <br> (e.g. 00:00:00,074 --> 00:00:02,564)
$subtitle <br> (e.g. Previously on Breaking Bad...)
by the way i have this code. but it doesn't see the lines. it must be edited but how?
$srt_file = file('test.srt',FILE_IGNORE_NEW_LINES);
$regex = "/^(\d)+ ([\d]+:[\d]+:[\d]+,[\d]+) --> ([\d]+:[\d]+:[\d]+,[\d]+) (\w.+)/";
foreach($srt_file as $srt){
preg_match($regex,$srt,$srt_lines);
print_r($srt_lines);
echo '<br />';
}
Here is a short and simple state machine for parsing the SRT file line by line:
define('SRT_STATE_SUBNUMBER', 0);
define('SRT_STATE_TIME', 1);
define('SRT_STATE_TEXT', 2);
define('SRT_STATE_BLANK', 3);
$lines = file('test.srt');
$subs = array();
$state = SRT_STATE_SUBNUMBER;
$subNum = 0;
$subText = '';
$subTime = '';
foreach($lines as $line) {
switch($state) {
case SRT_STATE_SUBNUMBER:
$subNum = trim($line);
$state = SRT_STATE_TIME;
break;
case SRT_STATE_TIME:
$subTime = trim($line);
$state = SRT_STATE_TEXT;
break;
case SRT_STATE_TEXT:
if (trim($line) == '') {
$sub = new stdClass;
$sub->number = $subNum;
list($sub->startTime, $sub->stopTime) = explode(' --> ', $subTime);
$sub->text = $subText;
$subText = '';
$state = SRT_STATE_SUBNUMBER;
$subs[] = $sub;
} else {
$subText .= $line;
}
break;
}
}
if ($state == SRT_STATE_TEXT) {
// if file was missing the trailing newlines, we'll be in this
// state here. Append the last read text and add the last sub.
$sub->text = $subText;
$subs[] = $sub;
}
print_r($subs);
Result:
Array
(
[0] => stdClass Object
(
[number] => 1
[stopTime] => 00:00:24,400
[startTime] => 00:00:20,000
[text] => Altocumulus clouds occur between six thousand
)
[1] => stdClass Object
(
[number] => 2
[stopTime] => 00:00:27,800
[startTime] => 00:00:24,600
[text] => and twenty thousand feet above ground level.
)
)
You can then loop over the array of subs or access them by array offset:
echo $subs[0]->number . ' says ' . $subs[0]->text . "\n";
To show all subs by looping over each one and displaying it:
foreach($subs as $sub) {
echo $sub->number . ' begins at ' . $sub->startTime .
' and ends at ' . $sub->stopTime . '. The text is: <br /><pre>' .
$sub->text . "</pre><br />\n";
}
Further reading: SubRip Text File Format
Group the file() array into chunks of 4 using array_chunk(), then omit the last entry, since it's a blank line like this:
foreach( array_chunk( file( 'test.srt'), 4) as $entry) {
list( $number, $time, $subtitle) = $entry;
echo $number . '<br />';
echo $time . '<br />';
echo $subtitle . '<br />';
}
That is not going to match because your $srt_file array might look like this:
Array
([0] => '1',
[1] => '00:00:00,074 --> 00:00:02,564',
[2] => 'Previously on Breaking Bad...'.
[3] => '',
[4] => '2',
...
)
Your regex isn't going to match any of those elements.
If your intent is to read the entire file into one long memory-hog-of-a-string then use file_get_contents to get the entire file contents into one string. then use a preg_match_all to get all the regex matches.
Otherwise you might try to loop through the array and try to match various regex patterns to determine if the line is an id, a time range, or text and do thing appropriately. obviously you might also want some logic to make sure you are getting values in the right order (id, then time range, then text).
I made a class to convert a .srt file to array.
Each entry of the array has the following properties:
id: a number representing the id of the subtitle (2)
start: float, the start time in seconds (24.443)
end: float, the end time in seconds (27.647)
startString: the start time in human readable format (00:00:24.443)
endString: the end time in human readable format (00:00:24.647)
duration: the duration of the subtitle, in ms (3204)
text: the text of the subtitle (the Peacocks ruled over Gongmen City.)
The code is php7:
<?php
namespace VideoSubtitles\Srt;
class SrtToArrayTool
{
public static function getArrayByFile(string $file): array
{
$ret = [];
$gen = function ($filename) {
$file = fopen($filename, 'r');
while (($line = fgets($file)) !== false) {
yield rtrim($line);
}
fclose($file);
};
$c = 0;
$item = [];
$text = '';
$n = 0;
foreach ($gen($file) as $line) {
if ('' !== $line) {
if (0 === $n) {
$item['id'] = $line;
$n++;
}
elseif (1 === $n) {
$p = explode('-->', $line);
$start = str_replace(',', '.', trim($p[0]));
$end = str_replace(',', '.', trim($p[1]));
$startTime = self::toMilliSeconds(str_replace('.', ':', $start));
$endTime = self::toMilliSeconds(str_replace('.', ':', $end));
$item['start'] = $startTime / 1000;
$item['end'] = $endTime / 1000;
$item['startString'] = $start;
$item['endString'] = $end;
$item['duration'] = $endTime - $startTime;
$n++;
}
else {
if ($n >= 2) {
if ('' !== $text) {
$text .= PHP_EOL;
}
$text .= $line;
}
}
}
else {
if (0 !== $n) {
$item['text'] = $text;
$ret[] = $item;
$text = '';
$n = 0;
}
}
$c++;
}
return $ret;
}
private static function toMilliSeconds(string $duration): int
{
$p = explode(':', $duration);
return (int)$p[0] * 3600000 + (int)$p[1] * 60000 + (int)$p[2] * 1000 + (int)$p[3];
}
}
Or check it out here: https://github.com/lingtalfi/VideoSubtitles
You can use this project: https://github.com/captioning/captioning
Sample code:
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Captioning\Format\SubripFile;
try {
$file = new SubripFile('your_file.srt');
foreach ($file->getCues() as $line) {
echo 'start: ' . $line->getStart() . "<br />\n";
echo 'stop: ' . $line->getStop() . "<br />\n";
echo 'startMS: ' . $line->getStartMS() . "<br />\n";
echo 'stopMS: ' . $line->getStopMS() . "<br />\n";
echo 'text: ' . $line->getText() . "<br />\n";
echo "=====================<br />\n";
}
} catch(Exception $e) {
echo "Error: ".$e->getMessage()."\n";
}
Sample output:
> php index.php
start: 00:01:48,387<br />
stop: 00:01:53,269<br />
startMS: 108387<br />
stopMS: 113269<br />
text: ┘ç┘à╪د┘ç┘┌»█î ╪▓█î╪▒┘┘ê█î╪│ ╪ذ╪د ┌ر█î┘█î╪ز ╪ذ┘┘ê╪▒█î ┘ê ┌ر╪»┌ر x265
=====================<br />
start: 00:02:09,360<br />
stop: 00:02:12,021<br />
startMS: 129360<br />
stopMS: 132021<br />
text: .┘à╪د ┘╪ذ╪د┘è╪» ╪ز┘┘ç╪د┘è┘è ╪د┘è┘╪ش╪د ╪ذ╪د╪┤┘è┘à -
┌╪▒╪د ╪ا<br />
=====================<br />
start: 00:02:12,022<br />
stop: 00:02:14,725<br />
startMS: 132022<br />
stopMS: 134725<br />
text: ..╪د┌»┘ç ┘╛╪»╪▒╪ز -
.╪د┘ê┘ ┘ç┘è┌┘ê┘é╪ز ┘à╪ز┘ê╪ش┘ç ╪▒┘╪ز┘┘à┘ê┘ ┘┘à┘è╪┤┘ç -<br />
=====================<br />
it can be done by using php line-break.
I could do it successfully
let me show my code
$srt=preg_split("/\\r\\n\\r\\n/",trim($movie->SRT));
$result[$i]['IMDBID']=$movie->IMDBID;
$result[$i]['TMDBID']=$movie->TMDBID;
here $movie->SRT is the subtitle of having format u posted in this question.
as we see, each time space is two new line,
hope u getting answer.
Simple, natural, trivial solution
srt subs look like this, and are separated by two newlines:
3
00:00:07,350 --> 00:00:09,780
The ability to destroy a planet is
nothing next to the power of the force
Obviously you want to parse the time, using dateFormat.parse which already exists in Java, so it is instant.
class Sub {
float start;
String text;
Sub(String block) {
this.start = null; this.text = null;
String[] lines = block.split("\n");
if (lines.length < 3) { return; }
String timey = lines[1].replaceAll(" .+$", "");
try {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss,SSS");
Date zero = dateFormat.parse("00:00:00,000");
Date date = dateFormat.parse(timey);
this.start = (float)(date.getTime() - zero.getTime()) / 1000f;
} catch (ParseException e) {
e.printStackTrace();
}
this.text = TextUtils.join(" ", Arrays.copyOfRange(lines, 2, lines.length) );
}
}
Obviously, to get all the subs in the file
List<Sub> subs = new ArrayList<>();
String[] tt = fileText.split("\n\n");
for (String s:tt) { subs.add(new Sub(s)); }

How to search a multidimensional array using GET

Hey guys, I've had a lot of help from everyone here and i am really appreciative! I'm trying to create a text file search engine and i think i am on the final stretch now! All i need to do now is to be able to search the multi-dimensional array i've created for a certain word submitted by a form and grabbed with GET, and return the results in highest to lowest order (TF-IDF will come later). I can perform a simple search on the content variable which is not really what i want (see in code for $new_content) but not on the $index array.
Here is my code:
<?php
$starttime = microtime();
$startarray = explode(" ", $starttime);
$starttime = $startarray[1] + $startarray[0];
if(isset($_GET['search']))
{
$searchWord = $_GET['search'];
}
else
{
$searchWord = null;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="wrapper">
<div id="searchbar">
<h1>PHP Search</h1>
<form name='searchform' id='searchform' action='<?php echo $_SERVER['PHP_SELF']; ?>' method='get'>
<input type='text' name='search' id='search' value='<?php echo $_GET['search']; ?>' />
<input type='submit' value='Search' />
</form>
<br />
<br />
</div><!-- close searchbar -->
<?php
include "commonwords.php";
$index = array();
$words = array();
// All files with a .txt extension
// Alternate way would be "/path/to/dir/*"
foreach (glob("./files/*.txt") as $filename) {
// Includes the file based on the include_path
$content = file_get_contents($filename, true);
$pat[0] = "/^\s+/";
$pat[1] = "/\s{2,}/";
$pat[2] = "/\s+\$/";
$rep[0] = "";
$rep[1] = " ";
$rep[2] = "";
$new_content = preg_replace("/[^A-Za-z0-9\s\s+]/", "", $content);
$new_content = preg_replace($pat, $rep, $new_content);
$new_content = strtolower($new_content);
preg_match_all('/\S+/',$new_content,$matches,PREG_SET_ORDER);
foreach ($matches as $match) {
if (!isset($words[$filename][$match[0]]))
$words[$filename][$match[0]]=0;
$words[$filename][$match[0]]++;
}
foreach ($commonWords as $value)
if (isset($words[$filename][$value]))
unset($words[$filename][$value]);
$results = 0;
$totalCount = count($words[$filename]);
// And another item to the list
$index[] = array(
'filename' => $filename,
'word' => $words[$filename],
'all_words_count' => $totalCount
);
}
echo '<pre>';
print_r($index);
echo '</pre>';
if(isset($_GET['search']))
{
$endtime = microtime();
$endarray = explode(" ", $endtime);
$endtime = $endarray[1] + $endarray[0];
$totaltime = $endtime - $starttime;
$totaltime = round($totaltime,5);
echo "<div id='timetaken'><p>This page loaded in $totaltime seconds.</p></div>";
}
?>
</div><!-- close wrapper -->
</body>
</html>
foreach ($index as $result)
if (array_key_exists($searchWord,$result['word']))
echo "Found ".$searchWord." in ".$result['filename']." ".$result['word'][$searchWord]." times\r\n";
As an aside, I would highly recommend only searching the files if the search term has been filled rather than searching with every refresh to the page.
Also, some other things to keep in mind:
- Make sure you declare variables before using them (such as your $pat and $rep variables, should be $pat = Array(); before using it).
- You do the right thing at the top and check for the existence of a $searchWord but keep referencing the $_GET['search']; I would advise continuing to use $searchWord and checking against is_null($searchWord) throughout the page instead of using $_GET. It's good practice to not just output those variables on the page without an integrity check.
- Also, it may be more useful to check if the $searchWord (or words) are in the $commonWords, then process the file. Could take some time off the search if there are a lot of files or big files with a lot of words. I also don't fully understand why you're storing all words when you are only looking for keywords, but if this gets too big you'll be hitting a memory limit in the near future.

Categories