I would like to use a textarea in html form to get the delimited data
for example:
The simple data is like the following
testA#testa.com peter USA
testB#testB.com Tony USA
testC#testC.com tom USA
testA#testa.com peter USA
testA#.com peter USA
The problems are:
How to check where is each line ends? (\n)?
How to do duplication checking (only for email)? (if 3 data each row, get 1,4,7,11...data, and array_unique?)
Should i restrict the deliminator symbol or i do something to check automatically?
What If space is deliminator , but at same time my other data eg. is using space e.g. Tony Hanks ?
Thank you for any kind of help
First I would split string by line ends:
$r = explode(PHP_EOL, $data); //data is your raw data from textarea
To check the delimiter, explode first line by all delimiters that are possible and check array count.
foreach( array(' ', ';', '/') as $delimiter) {
$x = explode($delimiter, r[0]);
if(count($x) == 3) {
break;
}
}
After that use proper delimiter with str-getcsv on raw data: http://www.php.net/manual/en/function.str-getcsv.php
What If space is deliminator , but at same time my other data eg. is using space e.g. Tony Hanks ?
In that case you need to use quotes. Excel also could not handle this without quotes.
How to do duplication checking (only for email)?
Create array where keys are emails. Iterate through your parsed csv and check if key isset already or not.
Related
I apologize if this question has a no brainer answer. I am still learning more ins and outs of php.
I have a snippet of code that is taking in a CSV file. This CSV file is uploaded by a user who downloads it from an external source. In the CSV file, the person's first name and last name is not split in separate columns. Therefore, in PHP the following is used:
$member_name = explode( " ", $application_data[5]);
The problem is that when this data is then used to render a PDF document to send a letter to the member, it cuts off their last name if their last name is two words.
The information is loaded into the PDF document with the first name and last name field by using:
$member_name[0],
$member_name[1]
Can I safely do:
$member_name[0],
$member_name[1] + $member_name[2]
Even if 99% of the members do not have a space in the last name? Will I get an error that member_name[2] doesn't exist 99% of the time this is done?
I've done some searching on array_merge. Is that a better option? I've been trying to search for how php handles when you add something that doesn't exist and I'm drawing a blank.
I don't want to assume my solution will work and then when the person uploads their CSV file tomorrow, they get an error.
Or maybe I'm looking at this the wrong way and before it attempts to render a pdf document, I should do an if statement that figures out if $member_name[2] exists.
Thank you!
You can use the limit parameter of explode to only split at the first space.
$member_name = explode( " ", $application_data[5], 2);
Of course, if the first name also has more than one word, this still won't be quite right. Names are tricky.
Regarding array_merge, I don't think it would really be useful in this situation.
You could just use a limiter on your explode to only seperate on the first space. Here is an example.
$name = "George The King";
print_r(explode(' ', $name, 2)); //prints -> Array ( [0] => George [1] => The King )
I need some assistance with php. I have been trying several things for the past several days including str_replace to no avail.
I have a field that may contain from 1 to 20 values, all listed on their own line, there is no html code in that field to separate them and some of the values may have their own spaces in between, so separating by space doesnt work.
What I need is to extract every single string of each line and convert it to code.
<p>For example, my field with values looks like this: </p>
<p><b>lang_fld </b><br>
------
<br>
English<br>
Spanish<br>
German<br>
French</p>
What I have in mind is to extract each line, ex. "English" from that string, and create a line of code like
<img src="images/flags/english.png> English
Basically I want to add the flag graphic to the word
I already tried
echo str_replace('English','<img src="images/flags/english.png>,lang_fld)<br>
...and so on
what I get after going through every single possible value is a bunch error
messages (different every time since I keep making changes - by guessing)
Can someone offer an easier option to do this? Not all 20 values will be in
that areatext field, some may contain just one language, some ten, some all 20,
etc.
Thank you!
Assuming you have all the values on a separate line, you can do explode() on the string to convert it to array of separate items, then loop through the array with foreach and perform any modifications with the single item. After you are done with the items and you would like to get them back together, you can use implode() to combine them into a single string.
A short sample ( you can of course use a for loop, I just prefer foreach here as it shows you better what is happening with the data ):
$text =
"French language
Italian language
English language";
$items = explode( "\n", $text ); // Split by newline ( you can also use "<br>" as separator )
$result = array(); // Modified data will be placed here
foreach ( $items as $item )
{
// Do something with $item
$item = "<img src=\"images/flags/$item.png\"> $item";
$result[] = $item;
}
// Merge them back together
$text = implode("\n", $result);
I have a text document with a slew of email addresses which I converted from a pdf.
here is an example of of what it looks like:
name1;someone#awebite1.com;;;
name2;someone#awebite2.com;;;
name3;someone#awebite3.com;;;
name4;someone#awebite4.com;;;
name5;someone#awebite5.com;;;
etc... 600+ contacts
anyone know to to write a simple php pattern/expression/regex I can use to separate the name and email one by one so I can put in database?
the database of course would be a simple: id | contact | email
any help would be gladly appreciated!
I forgot to mention, I would like to do it in php. I will incorporate the code into a form for future usage.
In PHP, you can split a string using the explode function..
$parts = explode(';', $inputString);
The returned array contains each part separated by ;.
For this, each line in your text document has to be given as inputString. So loop through the array returned by
preg_split('/\\n/',$docContent)
and call explode with each element. The above preg_splitreturns an array with each line of the input as an element.
Combining both,
$lines = preg_split('/\\n/',$docContent);
foreach($lines as $line) {
$parts = explode(';', $line);
//$parts[0] is name and $parts[1] is email. ignore remaining elements
}
Note : I have only a little knowledge in php. There may be better code.
How about something like:
LOAD DATA INFILE 'yourFile'
INTO TABLE yourTable
FIELDS TERMINATED BY ';'
LINES TERMINATED BY ';;;\n'
assuming that by "contact" you mean the very first field of each line (which says 'contact' for all shown values), something like this will work:
cat contacts.txt | awk {'split($2,A,";"); print A[1]"|"$1"|"A[2]}'
My idea is to use a textarea to let the user copy email name address etc.... to it.
The copied data must have delimiter between each value.
However, my questions are:
How can i detect the delimiter used in copied data?
How to manipulate? Store each into different array according to the location? but what if there is some error between eg. if one row has one more entry eg. email name address adress2 when other are email name address
Actually i am doing some process from outlook express export txt file or data copied from excel sheet
For those outlook express export file, there are some spacing for each email that without name .So the problem is occur eg.
aa#aa.com name1 bb#bb.com cc#cc.com name2
Thanks for your kindly help.
You would use explode for this (http://php.net/manual/en/function.explode.php).
If you can ask the users to enter each piece of data on a new line, you can then split the textarea contents by the \n character:
e.g.
$myarray = explode("\n", $textarea_str);
Then each element of the array can be split by the delimiting comma:
foreach ($myarray as $row)
$eachline[] = explode(",", $row);
Then validate the individual items that you've extracted from the delimited data as if they have come individually.
You have to explode(',', $_POST['emails]), then run trough that array and check/trim/validate-email all elements for proper format.
you can pre inform the user ,email address must be separated by (ur delimitor may be comma and so).On php side just explode(delimitor,$_REQUEST['text_area_name']);
Oh, nice question . You are trying to find what is the delimiter used in the copied text . I cannot say a perfect solution, but you may create an algorithm like this .
Consider possible delimiters ex : , ' " | etc.
Explode the text with each delimiter in consideration . count the number of elements returned in each array
For , which delimiter you got the higher number of elements in array , may be used by the user
You can fine tune the code
This is a simple example .
Thanks
Well, I need to parse 2 textfiles. 1 named Item.txt and one named Message.txt They are configuration files for a game server, Item contains a line for each item in the game, and Message has Item names, descriptions, server messages etc. I know this is far less than ideal, but I can't change the way this works, or the format.
The idea is in Item.txt I have lines in this format
(item (name 597) (Index 397) (Image "item030") (desc 162) (class general etc) (code 4 9 0 0) (country 0 1 2) (plural 1) (buy 0) (sell 4) )
If I have the php variable $item which is equal to 397 (Index), I need to first get the 'name' (597).
Then I need to open Message.txt and find this line
( itemname 597 "Blue Box")
Then return "Blue Box" to PHP as a variable.
What I'm trying to do is return the item's name with the item's Index.
I know this is probably something really basic, but I've searched though dozens of file operation tutorials and still can't seem to find what I need.
Thanks
Following method doesn't actually 'parse' the files, but it should work for your specific problem...
(Note: not tested)
Given:
$item = 397;
open Item.txt:
$lines = file('Item.txt');
search index $item and get $name:
$name = '';
foreach($lines as $line){ // iterate lines
if(strpos($line, '(Index '.$item.')')!==false){
// Index found
if(preg_match('#\(name ([^\)]+)\)#i', $line, $match)){
// name found
$name = $match[1];
}
break;
}
}
if(empty($name)) die('item not found');
open Message.txt:
$lines = file('Message.txt');
search $name and get $msg:
$msg = '';
foreach($lines as $line){ // iterate lines
if(strpos($line, 'itemname '.$name.' "')!==false){
// name found
if(preg_match('#"([^"]+)"#', $line, $match)){
// msg found
$msg = $match[1];
}
break;
}
}
$msg should now contain Blue Box:
echo $msg;
Not sure if your problem is with parsing the expressions, or reading files per se since you mention "file operation tutorials".
Those parenthetical expressions in your files are called s-expressions. You may want to google for an s-expression parser and adapt it to php.
You should look into the serialize function, which allows data to be stored to a textfile in a format that PHP can reinterpret easily when it needs to be reloaded.
Serializing this data as an array and saving it down to the textfiles would allow you to access it by array keys. Let's take your example. As an array, the data you described would look something like this:
$items[397]['name'] = 'bluebox';
Serializing the item array would put it in a format that could be saved and later accessed.
$data = serialize($items);
//then save data down to the text files using fopen or your favorite class
You could then load the file and unserialize it's contents to end up with the same array. The serialize and unserialize functions are directly intended for this application.
the first text file has several features that you can use to help parse it. It is up to you to decide if it is well formed and reliable enough to key on.
I noticed:
1) a record is delimited by a single line break
2) the record is further delimted by a set of parens ()
3) the record is typed using a word (e.g. item)
4) each field is delimited by parens
5) each field is named and the name is the first 'word'
6) anything after the first word is data, delimited by spaces
7) data with double quotes are string literals, everything else is a number
A method:
read to the end of line char and store that
strip the opening and closing parens
strip all closing )
split at ( and store in temp array (see: http://www.php.net/manual/en/function.explode.php)
element 0 is the type (e.g. item)
for elements 1-n, split at space and store in temp array.
element 0 in this new array will be the key name, the rest is data
once you have all the data compartmentalized, you can then store it in an associative array or database. The exact structure of the array is difficult for me to envision without actually getting into it.