In PHP, Removing first element in CSV String - php

I'm simply looking to take the first csv out of a string, using PHP. Here are a few examples:
"Sea Bass, Floured Or Breaded, Fried" => "Floured Or Breaded, Fried"
"Tuna, Fresh, Baked Or Broiled" => "Fresh, Baked Or Broiled"
"Croaker, Breaded Or Battered, Baked" => "Breaded Or Battered, Baked"
And so on...
Thank you.

You can try this:
$csvArray = explode(",", $csv);
array_shift($csvArray);
$newCsv = implode(",", $csvArray);

I suggest using str_getcsv or something similar that parses csv, this will take into account any quotation marks and commas in the CSV string. after that you can just array_shift

Related

PHP: Write comma to csv file

I've got a form which submits data to a csv file.
When a user inputs a comma to a field, it destroys my csv structure.
I want to convert inputted commas so that they can get displayed as a character.
I tried this:
$_POST["field"] = str_replace(",", "','", $_POST["field"]);
Use html encoding for instant relief , but still my recommendation to use phpExcel
$comma="&#44";
$_POST["field"] = str_replace(",", $comma, $_POST["field"]);
You can use fputcsv() to write, and fgetcsv() to read the file, it automatically converts your string.
A simple example for writing the data:
$csv = fopen('file.csv', 'w');
$array = array($csv);
fputcsv($csv, $array);
And reading the data:
$csv = fopen('file.csv','r');
print_r(fgetcsv($csv));
Probably not the best answer, but it does work.
You could replace the comma with a random string when inputting to the CSV as below:
$commastring = str_replace(",", "/zwdz/", $tempstring);
and then when you need to output the comma somewhere on your website (if a database website) you can do the opposite str_replace
You can escape coma like this:
$_POST["field"] = str_replace(",", "\,", $_POST["field"]);
Or you can put string in quotes
$_POST["field"] = "'".$_POST["field"]."'";

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.

TextArea to Array with 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).

delimited txt file to array? then update mysql PHP

How'd I go about reading a tab delimited .txt file and then coding it so it puts each column of data(that is seperated with a tab) into a php variable.
for example....
505050 somedata moredata
and then, writing these variables to
$id
$somedata
$moredata
I read into fgetcsv and making an array although it seemed to make the whole line an array i need to split it into variables so that i can write it to individual columns in the MySQL database,
Can anyone give me any pointers?
Thanks so much...
A combination of fgetcsv() and list() will be the most efficient way to split this into named variables:
list($id, $somedata, $moredata) = fgetcsv($fp, 0, "\t");
However, you do not need to have them as named variables in order to insert them in MySQL, you can just use the raw array returned by fgetcsv():
$row = fgetcsv($fp, 0, "\t");
$query = "
INSERT INTO `tablename`
(`id`, `somedata`, `moredata`)
VALUES
('{$row[0]}', '{$row[1]}', '{$row[2]}')
";
Don't forget to escape the data before using it in a query ;-)
explode() will split a string. Try this:
list($id, $somedata, $moredata) = explode("\t", $string);
Where $string is the string you want to split. For more info about explode() and list(), just look up on php.net.
You can use explode():
http://php.net/manual/en/function.explode.php

php convert string with new lines into array?

I am getting data from an API and the resulting string is
[RESPONSE]
PROPERTY[STATUS][0]=ACTIVE
PROPERTY[REGISTRATIONEXPIRATIONDATE][0]=2012-04-04 19:48:48
DESCRIPTION=Command completed successfully
QUEUETIME=0
CODE=200
RUNTIME=0.352
QUEUETIME=0
RUNTIME=0.8
EOF
I am trying to convert this into an array like
Array(
['PROPERTY[STATUS][0]'] => ACTIVE,
['CODE'] => 200,
...
);
So I am trying to explode it using the resulting file_get_content function with an explode like
$output = explode('=',file_get_contents($url));
But the problem is the returning values are not always returned in the same order, so I need to have it like $array['CODE'] = 200, and $array['RUNTIME'] = 0.352 however there does not seem to be any kind of new line characters? I tried \r\n, \n, <br>, \r\n\r\n in the explode function to no avail. But there is new lines in both notepad and the browser.
So my question is there some way to determine if a string is on a new line or determine what the character forcing the new line is? If not is there some other way I could read this into an array?
To find out what the breaking character is, you could do this (if $data contatins the string example you've posted):
echo ord($data[strlen('[RESPONSE]')]) . PHP_EOL;
echo ord($data[strlen('[RESPONSE]')+1]); // if there's a second char
Then take a look in the ASCII table to see what it is.
EDIT: Then you could explode the data using that newly found character:
explode(ord($ascii_value), $data);
Btw, does file() return a correct array?
Explode on "\n" with double quotes so PHP understands this is a line feed and not a backslashed n ;-) then explode each item on =
Why not just use parse_ini_file() or parse_ini_string()?
It should do everything you need (build an array) in one easy step.
Try
preg_split("/$/m", $str)
or
preg_split("/$\n?/m", $str)
for the split
The lazy solution would be:
$response = strtr($response, "\r", "\n");
preg_match_all('#^(.+)=(.+)\s*$#m', $response, $parts);
$parts = array_combine($parts[1], $parts[2]);
Gives you:
Array (
[PROPERTY[STATUS][0]] => ACTIVE
[PROPERTY[REGISTRATIONEXPIRATIONDATE][0]] => 2012-04-04 19:48:48
[DESCRIPTION] => Command completed successfully
[QUEUETIME] => 0
[CODE] => 200
[RUNTIME] => 0.8

Categories