first district entry with that key. * * @var array */ private $exact = array(); /** * Constructor. * * @param array $districts List of ['id' => int, 'en' => string, 'ar' => string]. */ public function __construct( array $districts ) { foreach ( $districts as $district ) { $keys = array_values( array_unique( array_merge( self::name_keys( isset( $district['en'] ) ? $district['en'] : '' ), self::name_keys( isset( $district['ar'] ) ? $district['ar'] : '' ) ) ) ); if ( empty( $keys ) ) { continue; } $entry = array( 'id' => (int) $district['id'], 'name' => isset( $district['en'] ) ? (string) $district['en'] : '', 'keys' => $keys, ); $this->index[] = $entry; foreach ( $keys as $key ) { if ( ! isset( $this->exact[ $key ] ) ) { $this->exact[ $key ] = $entry; } elseif ( false !== $this->exact[ $key ] && $this->exact[ $key ]['id'] !== $entry['id'] ) { // ABS has distinct districts with the same name (e.g. "Zahraa El Maadi" and // "Zahraa ElMaadi"); such a name cannot identify one district. $this->exact[ $key ] = false; } } } } /** * Comparable forms of a name. The prefix-stripped form is kept alongside the raw * form: ABS writes "ElMaadi" while customers write "Maadi", but always stripping * "al" would mangle "Alexandria". * * @param string $value Name. * @return string[] */ public static function name_keys( $value ) { $text = trim( mb_strtolower( (string) $value, 'UTF-8' ) ); if ( '' === $text ) { return array(); } $text = self::normalize_arabic( $text ); $text = trim( preg_replace( '/\s+/u', ' ', preg_replace( '/[^\p{L}\p{N}\s]/u', ' ', $text ) ) ); if ( '' === $text ) { return array(); } $keys = array( preg_replace( '/\s+/u', '', $text ) ); $latin = preg_replace( '/\s+/u', '', preg_replace( '/^(el|al)[\s-]*/u', '', $text ) ); $arabic = preg_replace( '/\s+/u', '', preg_replace( '/^ال/u', '', $text ) ); foreach ( array( $latin, $arabic ) as $key ) { if ( '' !== $key ) { $keys[] = $key; } } return array_values( array_unique( $keys ) ); } /** * Matches one name (a city field or a phrase). * * @param string $raw Name. * @return array|null ['id', 'name', 'distance', 'exact'] or null when there is no confident match. */ public function match( $raw ) { $result = $this->lookup( $raw ); return is_array( $result ) ? $result : null; } /** * Like match(), but tells "ambiguous" (false) apart from "nothing close" (null). * * @param string $raw Name. * @param bool $allow_fuzzy Whether to fall back to edit-distance matching. * @return array|null|false Match, null when nothing is close, false when several districts fit equally. */ private function lookup( $raw, $allow_fuzzy = true ) { $query_keys = self::name_keys( $raw ); if ( empty( $query_keys ) ) { return null; } // Keys are ordered most specific first (full name before prefix-stripped), so an // ambiguous full name is never rescued by a looser key that may be another district. foreach ( $query_keys as $key ) { if ( ! array_key_exists( $key, $this->exact ) ) { continue; } if ( false === $this->exact[ $key ] ) { return false; } return array( 'id' => $this->exact[ $key ]['id'], 'name' => $this->exact[ $key ]['name'], 'distance' => 0, 'exact' => true, ); } // Nothing longer than this is a district name; refusing it also bounds the work an // arbitrarily long customer-typed city could cause. if ( max( array_map( array( __CLASS__, 'length' ), $query_keys ) ) > self::MAX_KEY_LENGTH ) { return null; } // Short tokens (province codes, stray letters) are noise for fuzzy matching. if ( ! $allow_fuzzy || max( array_map( array( __CLASS__, 'length' ), $query_keys ) ) < 4 ) { return null; } $best = null; $runner_up = PHP_INT_MAX; foreach ( $this->index as $entry ) { $distance = PHP_INT_MAX; $matched_length = 0; foreach ( $query_keys as $query_key ) { foreach ( $entry['keys'] as $entry_key ) { $gap = abs( self::length( $query_key ) - self::length( $entry_key ) ); if ( $gap >= $distance || $gap > self::max_distance( self::length( $query_key ) ) ) { continue; } $candidate = self::levenshtein( $query_key, $entry_key ); if ( $candidate < $distance ) { $distance = $candidate; $matched_length = self::length( $query_key ); } } } if ( null === $best || $distance < $best['distance'] ) { if ( null !== $best ) { $runner_up = $best['distance']; } $best = array( 'id' => $entry['id'], 'name' => $entry['name'], 'distance' => $distance, 'matched_length' => $matched_length, 'exact' => false, ); } elseif ( $distance < $runner_up && $entry['id'] !== $best['id'] ) { $runner_up = $distance; } } if ( null === $best || $best['distance'] > self::max_distance( $best['matched_length'] ) ) { return null; } // Two districts equally close cannot be told apart; a wrong district misroutes the parcel. if ( $runner_up <= $best['distance'] ) { return false; } unset( $best['matched_length'] ); return $best; } /** * Scans free text for a district. When several appear, the one ending last wins * (Egyptian addresses put the district after the street); ties go to the longer phrase. * If the winning phrase is ambiguous, the result is null: the shorter name inside it * (e.g. "ElMaadi" inside "Zahraa ElMaadi") would be a different, wrong district. * * Phrases must match a district name exactly. Fuzzy matching across free text pairs * neighbouring words into false hits: against the live ABS list, "المعادي القاهرة" * (Maadi + Cairo) came within 3 edits of "مطار القاهره" (Cairo Airport). * * @param string $text Address text. * @return array|null Match, or null. */ public function match_in_text( $text ) { $words = preg_split( '/[^\p{L}\p{N}]+/u', trim( (string) $text ), -1, PREG_SPLIT_NO_EMPTY ); if ( empty( $words ) ) { return null; } $best = null; $best_end = -1; $best_words = 0; $count = count( $words ); for ( $start = 0; $start < $count; $start++ ) { for ( $size = 1; $size <= self::MAX_PHRASE_WORDS && $start + $size <= $count; $size++ ) { $match = $this->lookup( implode( ' ', array_slice( $words, $start, $size ) ), false ); if ( null === $match ) { continue; } // An ambiguous phrase competes like a match; if it wins, nothing is returned. $end = $start + $size; if ( null === $best || $end > $best_end || ( $end === $best_end && $size > $best_words ) ) { $best = $match; $best_end = $end; $best_words = $size; } } } return is_array( $best ) ? $best : null; } /** * Resolves an address: the city field alone first (typos tolerated), then the street * lines by exact name. City and governorate are not scanned with the street lines: * a trailing "Cairo" would otherwise outrank the district written before it. * * @param string $city City. * @param string $address1 Address line 1. * @param string $address2 Address line 2. * @return array|null Match with an added 'source' ('city' or 'address'), or null. */ public function match_address( $city, $address1, $address2 ) { $from_city = $this->match( $city ); if ( null !== $from_city ) { $from_city['source'] = 'city'; return $from_city; } $text = implode( ' , ', array_filter( array( $address1, $address2 ), 'strlen' ) ); $from_text = $this->match_in_text( $text ); if ( null !== $from_text ) { $from_text['source'] = 'address'; } return $from_text; } /** * Arabic letter folding and diacritic removal. * * @param string $text Text. * @return string */ private static function normalize_arabic( $text ) { $text = preg_replace( '/[\x{0617}-\x{061A}\x{064B}-\x{0652}\x{0670}\x{0640}]/u', '', $text ); return strtr( $text, array( 'أ' => 'ا', 'إ' => 'ا', 'آ' => 'ا', 'ى' => 'ي', 'ة' => 'ه', 'ؤ' => 'و', 'ئ' => 'ي', ) ); } /** * Allowed edit distance for a key length: short names collide quickly. * * @param int $length Key length in characters. * @return int */ private static function max_distance( $length ) { if ( $length <= 5 ) { return 1; } return $length <= 9 ? 2 : 3; } /** * Character length (multibyte-safe). * * @param string $value Value. * @return int */ private static function length( $value ) { return mb_strlen( $value, 'UTF-8' ); } /** * Levenshtein distance over characters; PHP's levenshtein() counts bytes, which breaks Arabic. * * @param string $a First string. * @param string $b Second string. * @return int */ private static function levenshtein( $a, $b ) { if ( $a === $b ) { return 0; } $a = preg_split( '//u', $a, -1, PREG_SPLIT_NO_EMPTY ); $b = preg_split( '//u', $b, -1, PREG_SPLIT_NO_EMPTY ); $m = count( $a ); $n = count( $b ); if ( 0 === $m ) { return $n; } if ( 0 === $n ) { return $m; } $previous = range( 0, $n ); for ( $i = 1; $i <= $m; $i++ ) { $current = array( $i ); for ( $j = 1; $j <= $n; $j++ ) { $cost = $a[ $i - 1 ] === $b[ $j - 1 ] ? 0 : 1; $current[ $j ] = min( $current[ $j - 1 ] + 1, $previous[ $j ] + 1, $previous[ $j - 1 ] + $cost ); } $previous = $current; } return $previous[ $n ]; } }