Mennyg
Mennyg

Reputation: 330

How to find the end of a word using strpos()

I'm getting an address input as one long string as opposed to name, address, city, state and zip. I split most of it up, besides for between the address and the city. So I want to search for any street type name (court, road, street, avenue, etc) and then split the string at the end of the word. Then I will be left with the address and city separate.

strpos() only gives me the position of the beginning of the keyword, I want it to split at the end of the keyword. For example this is where I'm up to:

John Doe
1 Main Street Anytown
NY
00000

I want to split between Street and Anytown. And this address won't be static, there may be more words etc.

Another idea would be a function that automatically splits a string into different fields. Someone told me that in some countries the postal service has an API that does it. Does USPS have such a thing? Their site doesn't indicate it.

Upvotes: 1

Views: 2437

Answers (4)

A.Tarhini
A.Tarhini

Reputation: 72

You can use explode function, which split a string using keyword and return an array of strings. Example of using explode:

$str = '1 Main Street Anytown';        
$array_of_string = explode('street',$str);    

Then $array_of_strings[0] will contains 1 Main and $array_of_strings[1] will contains Anytown

Upvotes: 0

Tuğca Eker
Tuğca Eker

Reputation: 1493

Actually what you should do is searching for multiple needle in haystack, summing position and length of needle.

function strpos_street($string){
    $types = [
   'court', 
   'road', 
   'street', 
   'avenue' 
  ];
  foreach($types as $t){
      $pos = strpos(strtolower($string), strtolower($t));
      if($pos === false) continue;
      else return $pos + strlen($t) - 1;
  }
  return -1;
}

echo strpos_street($string);

Some Tips:

  • Consider case sensivity
  • You may use explode function in a same iterative way
  • I'm not sure but there may be some addresses which contains both "street" and "avenue" words

Upvotes: 1

Chibueze Opata
Chibueze Opata

Reputation: 10054

It seems that you're trying to search in reverse as strpos gives position of a string starting from the beginning by default, you will need to set the offset to -1 and subtract from strlen.

i.e.

strlen($address) - strpos($address, 'Anytown', -1) - 1;
//search from reverse and output position starting from reverse

However as pointed out in the comments, this may not the best approach for the problem you're trying to sovle.

Upvotes: 0

Markus Laire
Markus Laire

Reputation: 2947

You could do something like this.

$word = "Street"

$pos = strpos($word, $address);
if ($pos !== false) {
    $pos += strlen($word) - 1;
    ...
}

Depending on how many different words to match there are, using regex might work better than using string functions.

Upvotes: 1

Related Questions