Split an Address Line in PHP - php

I'm using a the Royal Mail Postcode database to make sure I get the correct address details on my form. It pulls through the address into my form using the relevant input boxes. this is great, but I want to do is in the first input box the address may be something
123 The Street or Apartment 29 or even HouseName The Street. I post these within my form.
So the post is something like $_POST["line1"];
How is it possible to split the line into sections so that I can take the HouseNo or House Name from the address, so that on my next page I can show it as HouseNo/Name & Street Name?
Using the examples above output echo $houseno; - 123, echo $street; - The Street

try to split in two parts numeric and alpha
$example = $_POST["line1"];
list($alpha,$num) = sscanf($example, "%[A-Z a-z ]%d");
echo $alpha; // address in alpha with space
echo $num; // house no
For more :- PHP: Best way to split string into alphabetic and numeric components

You could use regular expressions to try and split up characters. Admittedly you'd then have two problems.
In general you're not going to find this very easy to do. You've posted some testcases:
123 The Street
Apartment 29
"The Orchard"
Here's a couple more to think about:
1A The Street
Flat B
Rather than attempting to process a free-form field with (literally) thousands of possible variations, why not provide an interface on the Royal Mail database (which you say you have)? Many sites give this option now:
You enter your postcode and (usually) house number
A box shows a list of matching addresses to choose from
You still get addresses which exactly match the Royal Mail database, but you now get the customer to do the tricky address-matching part of the process.
Of course, you should probably still let people enter freeform address data because the address database is sometimes a few steps behind reality...

Related

Incorrect results returned from a partial UK postcode

I am having an odd issue with Google Maps which their documentation doesn't seem to cover.
We have a page in our application that returns a list of engineer locations ordered by distance when an end user enters a postcode. We have recently noticed that some end users are entering partial UK postcodes (L1, BB7 or SE10).
These tend to be fine and work as intend but if the user searches for a partial postcode for the Manchester area they get odd results with distances of over 100 miles being returned.
I've researched this and it appears that Google is returning the locations for the motorway network where the road name matches the postal area in Manchester. For example: M4 is returning the motorway just north of Bristol instead of the city centre area.
The payload I am sending to Google is as follows:
$url="https://maps.google.com/maps/api/geocode/json?address={$address}&components=country:GB&key={$apikey}";
If I change the payload to this:
$url="https://maps.google.com/maps/api/geocode/json?components=country:GB|postal_code:{$address}&key={$apikey}";
I get ZERO_RESULTS from the API.
I saw this question from 2014 which is the identical issue but no resolution appears to have been found.
What am I doing wrong? Are there any workarounds that I could try to get slightly more accurate results? Am I better off restricting the inputs to full postcodes only?
I have come up with a rather messy hack that appears to solve my issue.
// Check if the postcode is a partial Mancunian postcode
if($postcode[0]==="M" && strlen($postcode) <= 4){
if($postcode[1]==6){
$manchester_postcode = "Salford ".$postcode;
}else{
$manchester_postcode = "Manchester ".$postcode;
}
$address=urlencode($manchester_postcode);
}else{
$address=urlencode($postcode);
}
$apikey=urlencode(env('GOOGLE_MAP_API'));
$url="https://maps.google.com/maps/api/geocode/json?address={$address}&components=country:GB&key={$apikey}";
If the postcode is identifiable as a partial (4 characters or less) and starts with the letter M, I prefix it with "Manchester". This solves all the mis-codings except for M6 which is still stubbornly selecting the motorway.
So I added in the check for the second character and change the prefix to "Salford". This resolves the problem.
For anyone else trying this solution you'll hit problems with the M60 postcode and some other random (non-Manchester) postcodes which route to equally random places (try E3 for example).
If you detect for any partial postcode and add 'postcode' after it (e.g. M60 postcode) it routes to the correct location.

Determine Country from Telephone Numbers

I have seen a few question on SO similar to what I require but nothing seems to fit the bill.
I am in the position where I need to deal with a call record and determine the country using the phone number. The number dialed can be any country for example:
44 7899455120 - UK
34 965791845 - Spain
355 788415235 - Albania
Obviously the world would be great if all calling codes were two digits but this is not the case. Currently I have a database full of countries and their relevant codes and in order to match I need to effectively take the first digit of the number ie 4 for the UK example and do a query of the database eg:
SELECT * from countries WHERE code LIKE '4%'
This may give me for example 20 results. So I loop again and do say
SELECT * from countries WHERE code LIKE '44%'
This may give me say one result, now I can determine it is UK. Some codes however like Albania are three digits and require more loops and database calls. This seems quite rudimentary and inefficient but as is I cannot think of another way to achieve this. I realise three calls to a database may not seem like much but if you have 1000 calls to deal with they soon add up.
Looking at the following question:
What regular expression will match valid international phone numbers?
There seems to be some great information on validating a number against country codes, but not so much on determining the country code from a number. Any advice or suggestions on a cleaner method would be much appreciated.
Spaces in the phone are shown for clarity
A library exists that will parse a string of digits and reformat it to international standards (a number like 4402081231234 to '+44 20 8123 1234'). It will also return the Phone Number region, 'GB' or 'US' from a number, if there is the country code embedded in the number.
https://github.com/googlei18n/libphonenumber The original library is in Java, but there are also versions in Javascript, Python, Ruby and PHP, among others.
There is no overlap ambiguity in the country codes. Meaning: the country code 11 is illegal because 1 is assigned to North America. Similarly, 20 is Egypt and there are no other country codes that start with 20. And the country codes that start with 21 are all 3 digits.
Since the is no overlap ambiguity, you can directly search for the country code in one query for the phone number 12125551212 like this:
select country
, code
from countrycodes
where code in ('121', '12', '1')
Again, there are no country codes 121 or 12, so the only criteria that will match is the 1.
Assuming the phone will always look like that:
$phone = "355 788415235"; // Albania
$parts = explode(" ", $phone);
$code = $parts[0]; // First part separated by space, 355.
Then query by that directly. No regular expression needed.
If that's not the case, consider separating the country code from the number on the input level.
On your system, every phone number has white space after country code so you can use it to determine country.
Create a table which has all country codes. Lıke
id | country | code
1 | Turkey | 90
2 | Spain | 34
(There is a table for you: http://erikastokes.com/mysql-help/country.sql.txt )
Than explode your phone number. Delimeter is white space " ".
$phoneNumber = "355 788415235";
$countryCode = explode(" ",$phoneNumber); // it divides phone number to two parts.
$countryCode = $countryCode[0]; // it returns 355. We write index 0 because country code is first part.
//Now you can call your country by country code.
$sqlQuery ="SELECT country FROM yourTableName WHERE code = '$countryCode' ";
...
//it will works like a charm. Because i currently using this.

Is there any way to find country code from phone number In php?

I want to find country code from the phone number because phone number is without country code(which is my input) for instance my phone no is 9xxxxxxxxx and I get result that number is from India and it will display then +919xxxxxxxxx in php.Is there any way to find country code from phone number?
First you'd need a source for the data listing every country, its code and the number of digits and pattern of the number. Then you'd need to put that into an associative array, matching up each country with it's country code. Then you'd need a bunch of preg_matches using regular expressions to determine if the first digits plus the regular expression matched the country in the array. You've talking a huge project to program this from scratch.
You can build your own PHP function for a lookup like this, a list of all the Phone Netnumbers can be found on Wikipedia. If there is no net number it's not possible to track the country since countries can use the same phone numbers.

How to validate if Textfield entered is a mobile number using php and SQL DB [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to validate phone number using PHP?
can anyone please help me know how to validate if the field value entered is a phone number using php...
I have used a variable $phone , datatype =varchar 10 in sql db
Now i want to validate that users enter only numbers in that field..
use preg_match
if(preg_match('/^(NA|[0-9+-]+)$/',$str)) {
*code here*
} else {
"code here"
}
One way to do this is with regular expressions. When validating phone numbers, it's easier on users if you accept accompanying characters, and filter them out yourself (-+()).
http://www.php.net/manual/en/function.preg-replace.php
$phone = preg_replace ( '/[+\\.\\(\\) ]/' , '' , $phone);
Once you've done that, checking for a match of 10 digits (assuming U.S. numbers with area code) can be done like so:
if(preg_match ( '/^\\d{10}$/', $phone) ) {
// Good match
}
http://www.php.net/manual/en/function.preg-match.php
Does is_numeric solve your problem?
Edit:
I wasn't aiming to solve OPs problem, merely hoping to give him/her pointers. However, reading the question closer makes me think that OP isn't being conscious of internationalisation issues. Her field is 10 characters long, so a number like +447970122467 (a valid British mobile number) would cause a failure. I'm going to assume they are in North America, and as such can assume that all numbers are in accordance with the North American Numbering Plan. The description of this, in words, is taken from that page:
Component Name Number ranges Notes
+1 ITU country calling code "1" is also the usual trunk code for accessing long-distance service between NANP numbers. In an intra-NANP context, numbers are usually written without the leading "+"
NPA Numbering Plan Area Code Allowed ranges: [2–9] for the first digit, and [0–9] for both the second and third digits. Covers Canada, the United States, parts of the Caribbean Sea, and some Atlantic and Pacific islands. The area code is often enclosed in parentheses.
NXX Central Office (exchange) code Allowed ranges: [2–9] for the first digit, and [0–9] for both the second and third digits. Often considered part of a subscriber number. The three-digit Central Office codes are assigned to a specific CO serving its customers, but may be physically dispersed by redirection, or forwarding to mobile operators and other services.
xxxx Subscriber Number [0–9] for each of the four digits. This unique four-digit number is the subscriber number or station code.`
That ought to be enough to get OP started on solving their problem. Sorry for being curt in my initial response.

Extract Company Address from a string

I need to extract an address from a string
$string ="some text 9 th pizza tower 78 main Chennai 600001. and other information may be phone number etc";
From $string I want to extract only "9 th pizza tower 78 main Chennai 600001"
This Address format is not constant it may be in two different way
one is string variable another one is like this
$string1= "some text 9 th pizza tower main Chennai 600001. and other information may be phone number etc";
From here I need to extract "9 th pizza tower main Chennai 600001"
I don't think this is possible...extracting text from a plain text file is like asking for a tree if you're in the woods, "Which one?".
If the file is always in the same format, like:
Company Name 73
1st Cross Street, Hotel Chennai
-600000
someadditionalstuff
Then you've got a change, or if it is always separated with a special character (, . ; etc.). If it is always the same format (the one you showed above), then something like this might work:
([a-zA-Z0-9 ]*),([a-zA-Z0-9 ]*) XXX ([a-zA-Z0-9 ]*) (-[0-9]{6})
Group 1: Company Name
Group 2: Address
Group 3: City
Group 4: Zip-Code
Bobby
Sorry this is not possible. It may work for one website but not for others as there is no standard format in displaying a company address(or any address) on a web page.
Not an easy question and there isn't a magic AI code that can figure it out.
You must make some assumption , and look at a lot of data to find out if it's good ones.
for start - if you assume, every address ends with ZIP code, and you can search the string for 5 (or 6) digits and cut it after that.
TO find the start of the address is beyond my skills. maybe looking for the first number.
you need to check a lot of examples to figure out what would be the best patten that match most of them.
Yes its possible by using Google natural Language processing which is paid or you can open natural language processing which is open. But for open NLP there is no better documentation available .
Better refer from this URL :
https://opennlp.apache.org/

Categories