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 )
Related
I'm using a PDF reader for PHP to load a big .pdf file that will store each page as a seperate, huge string in a big array.
This results in an output like this:
"Official certificate Surname: Doe First Name: John Date of birth:
10th of June, 1970 Place of Birth etc etc..."
How do I search for the specific text "Surname" and then select whatever text comes after that until "First Name" to return it as $var_surname.
The syntax used in the .pdf file will always be the same, so I have no problem using such absolute conditions for searching for the text.
I genuinely don't know where to start. Sorry if this question feels vague, let me know if more information is required.
if(preg_match('/Surname:[\s]+([\w]+)[\s]+First/i', $input, $matches)){
echo $matches[1];
}
will echo Doe
You could use a function like strrpos() to find out where the string surname ends, at what position. Then you could use strpos() to find out there the strin first name starts, what position. Afthr you know the positions you could chop between them and store it as $var_surnam . (using substr()). Hope this helps.
It would be better to figuring out the pattern and then write some methods. After that just pass the string by calling the methods. Based on given information this my best possible answer. Surely you will need to use builtin String methods.
I have a CSV file with three columns:
Mary,150203_15:29:12,150203_16:10:12
John,150203_15:29:17,pending
Peter,150203_15:29:35,150203_15:49:35
Olga,150203_15:30:43,pending
...
..
.
Mary,150204_15:42:14,pending
Peter,150204_20:42:14,pending
Because there are many entries on that file all I want to do is
find the latest entry according to the Username and change the last value (from pending to date()).
In the example above lets say I want to change the latest Mary entry in the 3rd column from pending to date. Then replace the updated CSV file with the current one.
Any ideas on how to approach that?
Thank you
You can work with the file as one huge string and do a string replacement.
$data = file_get_contents('your_file.csv');
$data = str_replace('Joe,150203_16:21:43,pending','Joe,15203_16:21:43,15204_15:23:43',$data);
file_put_contents('your_file.csv', $data);
The comments below raise a concern of finding out what the latest date is for a name. That is also rather simple to do. Assuming you've loaded $data in, as above...
$matches = array(); // Just to point out that this is an array
preg_match_all("/Joe,(.*),/", $data, $matches);
Now, $matches[1] contains all the dates for Joe. Did you ONLY want the ones that are pending? No problem...
preg_match_all("/Joe,(.*),pending/", $data, $matches);
Now, $matches[1] only contains the pending dates. Which is the most recent?
rsort($mathes[1]);
Now, $matches[1][0] is the most recent date. So, you can do:
$data = str_replace('Joe,'.$matches[1][0].',pending','Joe,'.$matches[1][0].',15204_15:23:43',$data);
Is this the absolute most efficient way to do this? No. Is it impossibly hard? No. You should look into using a proper database, but it is possible to use csv files.
If moving the data to a DB is not a solution in your case, you could do the following:
Read the CSV file into PHP via fgetcsv(), line by line, into an
array
Sort the array based on your criteria and get the latest entry
Update the entry
Write the entries back into the file via fputcsv()
I actually found a much simpler solution to this. Was the simplest one I could come up with.
$line = $_SESSION[username].",".$_SESSION[LOGIN_TIME].",".'pending'."\r\n";
$newline = $_SESSION[username].","$_SESSION[LOGIN_TIME].",".date("ymd_H:i:s"). "\r\n";
$data = file_get_contents('login.log');
$data = str_replace($line,$newline,$data);
file_put_contents('login.log', $data);
So there is no need for scanning for the latest entry. I just store the previous entry values and replace them with the new ones.
Thank you kainaw and BigScar
Good day all! I am working on a parser for a chat room that can color text based on who was talking for archive purposes. I have it working perfectly, except now the administrator wants to be able to remove the "fancy" names and replace with more readable versions for some of their regular people.
The chat room allows an extended range of letters and symbols to use, that, when transferred to a rtf file, may not exactly transfer fully.
I cant get it to work, and dont see any reason why it should not.
This is an example of what I have:
$nameconvert = array(
"îrúål__Þħōþħ" => "Eriel__Thoth",
);
***Scripting that parses an uploaded text
file line by line, each line places in an
array using space as delimiter... thus
name of person talking is $row_data[0]***
$name = $row_data[0];
$name = $nameconvert[$name];
** Code to throw everything back together **
Now, this is just a simplified snippet, but for whatever reason, it does not work. Now if I did $name = $nameconvert['îrúål__Þħōþħ'] then it does work, telling me that the name im putting in script, and name being pulled from mytext file are two different things, though they are visually identical
HELP!
I have found the answer, and wish to share my solution to others.
This is the modified code
$nameconvert = array(
"0123456789abcdef" => "Eriel__Thoth",
);
***Scripting that parses an uploaded text
file line by line, each line places in an
array using space as delimiter... thus
name of person talking is $row_data[0]***
$name = $row_data[0]
$name = $nameconvert[bin2hex(mb_convert_encoding($name,"UTF-8"))];
$name = $nameconvert[$name];
** Code to throw everything back together **
The command bin2hex(mb_convert_encoding($name,"UTF-8")) takes the name from the file, ensures it is in UTF-8 format, then creates its hexadecimal equivalent. It then uses that in the array to correspond to a easier to read name
It works just the way I am wanting!
I'm trying to make a form where the user can add their own 'questions + answers' to the quiz.
I loaded the original questions from a text file. The added questions will then be processed by process_editadd.php
<?php
session_start();
$file = fopen('data.txt', 'r');
$array=$_SESSION['questions_array'];
//make array out of values
$q=array($_POST['question'],$_POST['one'],$_POST['two'],$_POST['three'],$_POST['four']);
//add to file
$file=fopen("data.txt","w+");
fwrite($file, implode(',', $q)).
header('Location:module.php');
?>
The array adds onto the text file, but the problem is that it replaces the whole thing. I don't want the questions to replace the previous ones, I just want them added. Do you guys know what's wrong with the code?
Note: I'm not allowed using mySQL or Javascript
You could switch to using an actual database and make your life a lot easier... Failing that, look into fputcsv and fgetcsv to make it a slightly less tedious problem.
Your implode version right now is also vulnerable to CSV injection... you don't handle the case where any of the text you're writing MIGHT contain a comma. If it does, you'll suddenly find you'll have extra "columns" when you read the data back in later on.
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