0

I have a string containing an address and I need to know which street type that address is using. Here is an example:

$street = "100 road Overflow";
$streetTypes = array("ROAD", "ST", "ABBEY", "BLVD", "ALLEY", "CAR");

//find and save the street type in a variable

//Response
echo "We have found ".$streetType." in the string";

Also, the address is submitted by a user and the format is never the same which complicate things. So far, I've seen format like these:

100 ROAD OVERFLOW
100,road Overflow
100, Overflow road

What's the best way to address this problem?

  • Here is an answer already posted:http://stackoverflow.com/questions/13795789/check-if-string-contains-word-in-array. Not exactly what you need, but pretty close – Cayde 6 Feb 22 '16 at 17:22

2 Answers2

0

You need this:

$street = "100 road Overflow";
$streetTypes = array("ROAD", "ST", "ABBEY", "BLVD", "ALLEY", "CAR");

//find and save the street type in a variable
foreach($streetTypes as $item) {
    $findType = strstr(strtoupper($street), $item);
    if($findType){
        $streetType = explode(' ', $findType)[0];
    }
    break;
}

if(isset($streetType)) {
    echo "We have found ".$streetType." in the string";
} else {
    echo "No have found street Type in the string";
}
Vinícius Medeiros
  • 2,763
  • 1
  • 11
  • 12
0

Starting with your string, and the set of words you're looking for:

$street = "100 road Overflow";
$streetTypes = array("ROAD", "ST", "ABBEY", "BLVD", "ALLEY", "CAR");

first convert the string to uppercase and split it using preg_split. The regex I used will split it on whitespace or commas. You may have to experiment with it to get something that works based on your varying input.

$street_array = preg_split('/[\s*|,]/', strtoupper($street));

After the original string is an array, you can use array_intersect to return any words that match the target set of words.

$matches = array_intersect($streetTypes, $street_array);

Then you can do whatever you want with the matched words. If you only want to show one match, you should prioritize your list in $streetTypes so the the most important match is first (if there is such a thing). Then you can display it using:

if ($matches) {
    echo reset($matches);
}

(You should not use $matches[0] to show the first match, because keys will be preserved in array_intersect and the first item may not have index zero.)

Don't Panic
  • 41,125
  • 10
  • 61
  • 80