I want to take data entered in this format:
John Smith
123 Fake Street
Fake City, 55555
http://website.com
and store the values in variables like so:
$name = 'John Smith';
$address = '123 Fake Street';
$city = 'Fake City';
$zip = '55555';
$website = 'http://website.com';
So first name will be whatever is entered on the first line
address is whatever is on the second line
city is whatever is entered on the third line before the comma seperator
zip is whatever is on the third line after the comma
and website is whatever is on the fifth line
I don't want the pattern rules to be stricter than that. Can someone please show how this can be done?
$data = explode("\n", $input);
$name = $data[0];
$address = $data[1];
$website = $data[3];
$place = explode(',', $data[2]);
$city = $place[0];
$zip = $place[1];
Well, the regex would probably be something like:
([^\r]+)\r([^\r]+)\r([^,]+),\s+?([^\r]+)\r(.+)
Assuming that \r is your newline separator. Of course, it'd be even easier to use something like explode() to split things in to lines...
If you want something more precise, you could use this:
$matches = array();
if (preg_match('/(?P<firstName>.*?)\\r(?P<streetAddress>.*?)\\r(?P<city>.*?)\\,\\s?(?P<zipCode>.*?)\\r(?P<website>.*)\\r/s', $subject, $matches)) {
var_dump( $matches ); // will print an array with the parts
} else {
throw new Exception( 'unable to parse data' );
}
cheers
Related
It's relatively a common requirement to split a string from a potential splitter:
$name = 'John'; // or can be 'John Smith'
I use
list($firstName, $lastName) = explode(' ', $name) + [1 => null];
or
#list($firstName, $lastName) = explode(' ', $name);
I wonder if you guys use a more concise or more legible method for this?
Oh, I found it!
list($firstName, $lastName) = explode(' ', $name.' ');
The simple trick is appending the glue string to the end of the main string. Tadda!
This make accessing to the second part of the string really easy:
$domain = explode('#', $filter->email . '#')[1]; // for an invalid input the domain will be ''.
Use array_pop to get last_name and all in first_name. Your code not works for name which have three words. Example below also works for three words in name like Niklesh Kumar Raut
Uncomment one $name and comment two to check
//$name = "Niklesh";
//$name = "Niklesh Raut";
$name = "Niklesh Kumar Raut";
$name_arr = explode(" ",$name);
$last_name = array_pop($name_arr);
$first_name = implode(" ",$name_arr);
echo "First Name : $first_name\n";//Niklesh Kumar
echo "Last Name : $last_name";//Raut
Live demo : https://eval.in/871971
you can use regex to check if the string contains space in between, and then explode using the space to get the first and last string.
$name = 'john smith';
$first_name = $name;
$last_name = '';
if(preg_match('/\s/',$name)) {
list($first_name, $last_name) = explode(' ', $name);
}
echo "Hello ".$first_name." ".$last_name;
i have got an URL:
http://website.example/script.php?timestamp=2014-10-31T16%3A12%3A57&sms=PM+000+name
and i want to catch values separated by '+'
if there is ability to add to array or what:
array sms[
array_value1 = PM
array_value2 = 000
array_value3 = name]
and then take value like
$name1 = $array_value3;
which will be "name"
Also if it would be done from this:
$timestamp = "2014-10-31T16%3A12%3A57";
this:
$timestamp = "2014-10-31-16:12:37";
Thanks for reply.
$foo = explode(' ', $_GET['sms']); // array('PM','000','name')
That what you're after? The + is just an encoding for a space (%20), so server-side you're looking at splitting it by spaces (though they would all fall under the same parameter).
Keep in mind if "name" turned into "name surname", you'll end up with a 4th array element containing "surname". (Array('PM','000','name','surname'))
$url=urldecode("http://website.example/script.php?timestamp=2014-10-31T16%3A12%3A57&sms=PM+0+name");
$url=parse_url($url, PHP_URL_QUERY);
$url_split = explode('&', $url);
$timestamp=$url_split[0];
$sms=explode(' ', $url_split[1]);
Close but i wanted right this:
$raw = $_GET["sms"];
list($type, $number, $user) = explode(" ", $raw, 3);
and echo $user would give result: name
Now need to do somethink with that time formatting.
I'm having some trouble parsing a first name and last name from a string into 2 different variables.
The string is always in this format: "Smith, John" or "Doe, Jane"
Is there a function out that can split the first and last name to 2 different variables to something like...
$firstname = "John"
$lastname = "Smith"
Use list with explode like this:
list($firstname, $lastname) = explode(',', $yourString);
You may need to use trim to remove any whitespace from those vars.
explode() splits a string based upon another string and returns an array.
You could do:
$name = "Smith, John";
$name_array = array();
$name_array = explode(",", $name);
I would go with regexp for this so that there could be slight variations in the input (i.e. "Smith, John", "Smith ,John", "Smith , John" or "Smith,John")
You could do something like this for regexp "\w([a-z]+)\w" and then last name would be your first match and first name would be your second match.
$name = "Smith, John";
$expl = explode(', ', $name);
$firstname = $expl[1];
$lastname = $expl[0];
echo $firstname.' '.$lastname;
I have a text file containing data/fields which are separated by exact column no. Each new line represents a new row of data.
Example of file content:
John Chow 26 543 Avenue Street
From the above, first 10 columns are for the name. Next two are for age. And the rest are for the address.
I need to segregate those data from the uploaded file and display it to the user in a formatted table, which will later on be inserted into the database upon confirmation by user.
I am new to PHP. I think substr could work.
Please guide me on how to go about it. I am using codeigniter with PHP, but basic steps in plain PHP will do. Thanks
Read every line of the file, and parse the lines with either substr or regular expression:
$data = array();
$h = fopen($uploadedfile,"r");
while (false !== ($line = fgets($h)))
{
/* substring way: */
$data[] = array(
'name' => trim(substr($line,0,10)),
'age' => intval(sbstr($line,10,2),10),
'address' => trim(substr($line,12))
);
/* regular expression way: */
preg_match("'^(.{10})(.{2})(.*)$'",$line,$n);
$data[] = array(
'name' => trim($n[1]),
'age' => intval($n[2],10),
'address' => trim($n3)
);
}
fclose($h);
Then iterate the $data array to display it in a table form.
Edit: what you ask in the comments can be done also with regular expressions. If $val is the parsed 10 character string, then:
$val = preg_replace("'^0*'","",$val);
would replace all leading 0s.
Yes, you should be using substr. This extracts part of the string. Something like:
$name = trim(substr($line, 0, 10));
$age = trim(substr($line, 10, 2));
$addr = trim(substr($line, 12));
I've added trim to remove any extra whitespace.
Umm I suggest you don't use substr, because peoples names are not always going to be the same length so this will create some problems. I think the explode and implode functions would do the trick better for you, they split a string into an array and back.
http://php.net/manual/en/function.explode.php
http://www.php.net/manual/en/function.implode.php
<?PHP
$str = "John Chow 26 543 Avenue Street";
$data = explode(" ", $str);
$first_name = $data[0];
$last_name = $data[1];
$age = $data[2];
$address = implode(" ", array_slice($data, 3));
?>
You can use a regexp:
if (preg_match('/(.{10})(.{2})(.{12})/', $input, $output)) {
var_dump($output);
}
I have created a form that has a name and email address input.
Name: John Smith
Email: johnsmith#example.com
What I want to do is split the name in to first name and surname from the posted.
How would I go about doing this?
Assuming you are escaping user input and there is a validation to add space between name.
If that is already not implemented you could implement them otherwise consider to use separate input box for both first name and last name.
$name=explode(" ",$_POST['name']);
echo $name[0]; //first name
echo $name[1];// last name
$user = 'John Smith';
list($name, $surname) = explode(' ', $user);
$name_array = explode(" ",$name);
A quick way is to use explode(). But note that this will only work if there is only one space in it.
$name = "John Smith";
$parts = explode(' ', $name);
$firstName = $parts[0];
$surname = $parts[1];