TextArea to Array with PHP - php

I'm trying to figure out how to convert html textarea into php array,
I've used a form with POST to deliver the query to the php script,
and the php file is getting them with the following line:
$ids = array($_POST['ids']);
Needless to say that it puts everything into one line
Array ( [0] => line1 line2 line3 line4 )
I need the final results to replace this:
$numbers = array(
"line1",
"line2",
"line3",
"line4"
);
What would be the best approach to divide and re-parse it ?

Using an explode on \n is a proper way to get new lines. keep in mind though that on some platforms the end of line is actually send by \r\n, so just exploding on \n could leave you with extra data on the end of each line.
My suggestion would be to remove the \r before exploding, so you dont have to loop through the entire array to trim the result. As a last improvement, you dont know that there actually is a $_POST['ids'], so always check it first.
<?
$input = isset($_POST['ids'])?$_POST['ids']:"";
//I dont check for empty() incase your app allows a 0 as ID.
if (strlen($input)==0) {
echo 'no input';
exit;
}
$ids = explode("\n", str_replace("\r", "", $input));
?>

I would've done the explode by Hugo like this:
$ids = explode(PHP_EOL, $input);
manual Predefined Constants
Just my two cents...

Use this
$new_array = array_values(array_filter(explode(PHP_EOL, $input)));
explode -> convert textarea to php array (that lines split by new line)
array_filter -> remove empty lines from array
array_values -> reset keys of array

If the textarea simply has line breaks per entry then I'd do something like:
$ids = nl2br($_POST['ids');
$ids = explode('<br />',$ids); //or just '<br>' depending on what nl2br uses.

Try with explode function:
$ids = $_POST['ids']; // not array($_POST['ids'])
$ids = explode(" ", $ids);
The first parameter is the delimiter which could be space, new line character \r\n, comma, colon etc. according to your string from the textarea (it's not clear from the question whether values are separated by spaces or by new lines).

Related

How to fix white space error in array_count_value

i am making php array count value function i am taking values from file get content and using it in it and want to count values but due to space its not working properly Here is my codes
$data = file_get_contents('testr.txt');
preg_match_all('#mob:-(\S+)-#',$data,$matches);
$nu=$matches[1];
$n=implode($nu,',');
$n="9024453561,9024453561,9024453561,9024453561,9024453561 ";
//in value of $n i am getting spce at end so array_count _value not working
$array = array($n);
$counts = array_count_values($array);
echo $counts['9024453561'];
Using array_map(), map over your data where your call implode like so:
$n=array_map('trim', implode($nu,','));
This will remove any white space you have in your array values.
Hope that helps,
You do not split the string into an array by array($n). Instead you get a single element containing the entire string including commas. Use trim and preg_split to get an array of values.
$n="9024453561,9024453561,9024453561,9024453561,9024453561 ";
$array = preg_split('~\\s*,\\s*~u', trim($n));
$counts = array_count_values($array);
echo $counts['9024453561'];
This also splits a string like " 123 , 456 , 789 ". \s* means zero or more whitespaces. The double slash is to escape the slash in the string literal. trim removes spaces from the begin and the end of the entire string.
There is no need to go through the implode at all, just call array_count_values on your preg_match_all result:
$data = file_get_contents('testr.txt');
preg_match_all('#mob:-(\S+)-#',$data,$matches);
$nu=$matches[1];
$counts = array_count_values($nu);
echo $counts['9024453561'];

PHP fwrite function new line

i have this code:
//This line is for the input that i've looped above my code, it's a URL
$textAr[$i] = str_replace("\r\n","", $textAr[$i]);
//This is for implode purposes
$finalArray = array($textAr[$i], $m1, $m2, $m3, $m4, $m5, $m6);
//When i echo this variable, $test, the URL is in the line along with the implode arrays
$test = implode($finalArray, "***");
echo $test."\n";
//This is for writing into my text file
fwrite($sitesTxt, implode($finalArray, "***")."\n");
I'm having the kind of error where after i input a 3 URLs, the first and second URL has new line after i write in the file, but the last URL I've input is in line along with the imploded arrays. I've even trimmed the $textArr, but i keep getting the new lines.
Expected output:
https://docs.google.com***false***false***false***false***false***false***
https://stackoverflow.com***false***false***false***false***false***false***
https://stackexchange.com***false***false***false***false***false***false***
Output i'm getting at the txt file:
https://docs.google.com
***false***false***false***false***false***false***
https://stackoverflow.com
***false***false***false***false***false***false***
https://stackexchange.com***false***false***false***false***false***false***
Depending on your system, your lines may not end with a \r\n combination, but perhaps just \r.
I suggest either change str_replace to:
$textAr[$i] = str_replace(array("\r","\n"),"", $textAr[$i]);
Or, change the array:
$finalArray = array(trim($textAr[$i]), $m1, $m2, $m3, $m4, $m5, $m6);
Incidentally, although it will work, your implode parameters are reversed:
$test = implode("***", $finalArray);
You should use PHP_EOL constant for 'break-line' character. Because the break-line character in DOS is \r\n, but in *nix, it's just \n.
So, you replace the first line to
$textAr[$i] = str_replace(PHP_EOL, '', $textAr[$i]);

How to make a list to keyword list with PHP

I want to do something with PHP .
I have this list of names :
first
second
third
forth
Now i want to have this :
first,second,third,forth
How can this happen with a little PHP code ?
Assuming that you have those in array
$arr=array('first','second');
$str=implode(",",$arr);
EDIT(assuming each names are on the new line, i will replace \n with ,)
$str=file_get_contents("filename.txt");
$newstr=str_replace("\n",',',$str);
$newstr=trim($newstr, ",");//to remove the last comma
echo $newstr;
i think you text tag based on new line, so try this
first
second
third
forth
$arr = explode("\n", $txt);
echo implode(",",$arr);
every new line consider as a array value.
This is really basic PHP, I can't believe it isn't covered in most tutorials.
$array = file("filename", FILE_IGNORE_NEW_LINES);
$string = implode(',', $array);
I think you're looking for explode, like so http://us2.php.net/explode
array explode ( string $delimiter , string $string [, int $limit ] )
You want to set $delimiter to ' ', $string can be a copy -> paste of your text.txt content.
The best thing to do would be: take the text.txt content and use search-replace to remove new lines and add spaces (or commas), so you go from
ron
john
kahn
to ron, john, kahn, at which point you can import an array for use in php.

How to create array with this in php

I have list in html text arealike this.
12345
23456
12345
78938
85768
my question, how to get the list and create new array with list format..?
sorry about my english
It's unclear what you mean, exactly, but I am assuming you have a list of numbers, separated by line breaks. In that case, you can do this:
explode("\n", $the_string);
If you need to strip out carriage returns (like on Windows), do this:
explode("\n", preg_replace("/\r/", "", $the_string));
jQuery : Get textarea value and replace new line with comma
var txtval = $.trim($("#txtareaid").val()).replace(/\r?\n/g, ',');
// PASS jQuery variable to PHP
PHP: explode() function to convert string into an array based on comma
$a = txtval;
print_r(explode(',', $a));
First You want to Create Array Then,
Use it
$arr1 = array("12345","23456","12345");
echo "I want need".$arr1[0]."";
Say you submit the form to 1.php
code(1.php)
$text=$_REQUEST['t1'];
$arr=explode("\n", trim($text));//$arr is the array of all the entries in the textarea with name 't1'

Imploding $_POST values with comma

I have a textarea in my form where user will enter data line by line. I am processing it using $_POST . I have to separate each line by a comma while echoing it in php
the text area content like this
233
123
abf
4c2
I tried with below code
$array = array($_POST['devices']);
$device = implode(",", $array);
echo $device;
But it not showing commas between each value, rather I will get plain values like
233 123 abf 4c2
How can I show it like
233,123,abf,4c2
All above values are part of the text area,
You can not split a string into an array simply by creating an array().
You need to convert it to an array by splitting the lines:
$devices = preg_split('/\s+/', $_POST['devices']);
echo implode(',', $devices');
Note: You may want to split strictly on line endings. But the above will get you started.
No need to summon the power of regular expressions. You can simply implode the results of an explode.
$str = implode(",", explode("\n", $_POST['devices']));

Categories