function compare($debug = false)
 {
     $first = $this->str1;
     $second = $this->str2;
     $this->levenshtein = levenshtein($first, $second);
     $this->similarity['value'] = $sim = similar_text($first, $second, $perc);
     $this->similarity['percentage'] = $perc;
     if ($debug) {
         echo "{$first} | {$second}<br>";
         echo "leven: " . $this->levenshtein;
         echo '<br>similarity: ' . $sim . ', ' . $perc . '%<br><br>';
     }
     $soundex1 = soundex($first);
     $soundex2 = soundex($second);
     $this->soundex['levenshtein'] = levenshtein($soundex1, $soundex2);
     $this->soundex['similarity'] = $sim = similar_text($soundex1, $soundex2, $perc);
     $this->soundex['percentage'] = $perc;
     if ($debug) {
         echo "Soundex: " . $soundex1 . ", " . $soundex2 . "<BR>";
         echo 'levenshtein: ' . $this->soundex['levenshtein'] . '<br>';
         echo 'similarity: ' . $sim . ', ' . $perc . '%<br><br>';
     }
     $m1 = metaphone($first);
     $m2 = metaphone($second);
     $this->metaphone['levenshtein'] = levenshtein($m1, $m2);
     $this->metaphone['similarity'] = $sim = similar_text($m1, $m2, $perc);
     $this->metaphone['percentage'] = $perc;
     if ($debug) {
         echo "metaphone: " . $m1 . ", " . $m2 . "<br>";
         echo 'levenshtein: ' . $this->metaphone['levenshtein'] . '<br>';
         echo 'similarity: ' . $sim . ', ' . $perc . '%<br>';
         echo '<br>-------------------<br>';
     }
 }
Example #2
0
 /**
  *
  * @param string $word
  * @param array $words
  * @return array
  */
 public static function similarWord($word, array $words)
 {
     $similarity = config('pages.similar.similarity');
     $metaSimilarity = 0;
     $minLevenshtein = 1000;
     $metaMinLevenshtein = 1000;
     $result = [];
     $metaResult = [];
     foreach ($words as $n) {
         $minLevenshtein = min($minLevenshtein, levenshtein($n, $word));
     }
     foreach ($words as $n => $k) {
         if (levenshtein($k, $word) <= $minLevenshtein) {
             if (similar_text($k, $word) >= $similarity) {
                 $result[$n] = $k;
             }
         }
     }
     foreach ($result as $n) {
         $metaMinLevenshtein = min($metaMinLevenshtein, levenshtein(metaphone($n), metaphone($word)));
     }
     foreach ($result as $n) {
         if (levenshtein($n, $word) == $metaMinLevenshtein) {
             $metaSimilarity = max($metaSimilarity, similar_text(metaphone($n), metaphone($word)));
         }
     }
     foreach ($result as $n => $k) {
         if (levenshtein(metaphone($k), metaphone($word)) <= $metaMinLevenshtein) {
             if (similar_text(metaphone($k), metaphone($word)) >= $metaSimilarity) {
                 $metaResult[$n] = $k;
             }
         }
     }
     return $metaResult;
 }
 function search_items()
 {
     $search_string = $this->input->post('keyword');
     $search_string = preg_replace('/[^a-zA-Z0-9_ %\\[\\]\\.\\(\\)%&-]/s', '', $search_string);
     $words = explode(" ", $search_string);
     $data = $this->browse_gallery_model->get_all_search_strings();
     $row = 0;
     $row_array = array();
     $ad_array = array();
     foreach ($data as $text) {
         $text_word = explode("~", $text['Title_Text']);
         $ad_id = $text['ad_id'];
         $count = 0;
         foreach ($text_word as $single) {
             foreach ($words as $keyword) {
                 if (soundex(strtoupper($keyword)) == soundex(strtoupper($single)) || metaphone(strtoupper($keyword)) == metaphone(strtoupper($single))) {
                     $count = $count + 1;
                 }
             }
         }
         if (intval($count) > 0) {
             array_push($row_array, $ad_id);
         }
     }
     if (!empty($row_array)) {
         $data['ads'] = $this->browse_gallery_model->get_gallery_ads_by_adid($row_array);
         $data['top'] = $this->browse_gallery_model->get_top_categories();
         $this->load->view('search_items_view', $data);
     } else {
         $data['ads'] = NULL;
         $data['top'] = $this->browse_gallery_model->get_top_categories();
         $this->load->view('search_items_view', $data);
     }
 }
Example #4
0
 public function testStringPreparation()
 {
     $string = new String();
     $testString = "This is my-book title. BY Jesse.";
     $actual = $string->prepare($testString);
     $expected = [metaphone('this'), metaphone('book'), metaphone('title'), metaphone('jesse')];
     $this->assertEquals($actual, $expected);
 }
Example #5
0
function compareMetaphone($v1, $v2)
{
    $v1 = metaphone($v1);
    $v2 = metaphone($v2);
    similar_text($v1, $v2, $p);
    // return similarity percentage
    return $p;
}
Example #6
0
function strmp($str)
{
    $arr = explode(' ', $str);
    foreach ($arr as $ind => $word) {
        $word = trim($word);
        $arr[$ind] = metaphone($word);
    }
    $str = implode(' ', $arr);
    return $str;
}
Example #7
0
 public function testMultipleFind()
 {
     $redis = m::mock('Illuminate\\Redis\\Database');
     $redis->shouldReceive('sinter')->times(2)->andReturn([1], []);
     $string = m::mock('Reach\\String');
     $string->shouldReceive('prepare')->times(2)->andReturn([metaphone('the'), metaphone('story')], [metaphone('the'), metaphone('story')]);
     $string->shouldReceive('stripPunctuation')->times(2)->andReturn('books', 'authors');
     $reach = new Reach($redis, $string);
     $expected = ['books' => [1], 'authors' => []];
     $this->assertEquals($reach->findIn(['books', 'authors'], 'the story'), $expected);
 }
Example #8
0
function similar_phase($a, $b)
{
    $a = metaphone($a);
    $b = metaphone($b);
    $na = strlen($a);
    $nb = strlen($b);
    $n = $nb;
    if ($na > $nb) {
        $n = $na;
    }
    return levenshtein($a, $b) * 100.0 / $n;
}
Example #9
0
 /**
  * Prepare a string to have it's pieces inserted into the search index
  *
  * @param string $term
  * @return array
  */
 public function prepare($string)
 {
     $string = strtolower($this->stripPunctuation($string));
     $string = str_replace("-", " ", $string);
     $terms = explode(" ", $string);
     $prepared = [];
     foreach ($terms as &$t) {
         if (!$this->isStopWord($t) and strlen($t) >= 3) {
             $prepared[] = metaphone($t);
         }
     }
     return $prepared;
 }
function formatRecord($person, $merge_with = array())
{
    $base_person = array('pidm' => '', 'wpid' => '', 'psu_id' => '', 'username' => '', 'email' => '', 'msc' => '', 'name_first' => '', 'name_first_formatted' => '', 'name_first_metaphone' => '', 'name_last' => '', 'name_last_formatted' => '', 'name_last_metaphone' => '', 'name_middle_formatted' => '', 'name_full' => '', 'phone_of' => '', 'phone_vm' => '', 'emp' => '0', 'stu' => '0', 'stu_account' => '0', 'dept' => '', 'title' => '', 'major' => '', 'has_idcard' => '0');
    $person['office_phone'] = PSU::stripPunct($person['office_phone']);
    $person['phone_number'] = PSU::stripPunct($person['phone_number']);
    if ($merge_with) {
        $merge_with = PSU::params($merge_with, $base_person);
        $person = PSU::params($person, $merge_with);
    } else {
        $person = PSU::params($person, $base_person);
    }
    //end else
    $final = array('pidm' => $person['pidm'], 'wpid' => $person['wp_id'], 'psu_id' => $person['psu_id'], 'username' => !strpos($person['username'], '@') ? trim($person['username']) : substr($person['username'], 0, strpos($person['username'], '@')), 'email' => !strpos($person['email'], '@') ? trim($person['email']) : substr($person['email'], 0, strpos($person['email'], '@')), 'msc' => $person['msc'] ? $person['msc'] : '', 'name_first' => PSU::stripPunct($person['first_name']), 'name_first_formatted' => $person['first_name'], 'name_first_metaphone' => metaphone(PSU::stripPunct($person['first_name'])), 'name_last' => PSU::stripPunct($person['last_name']), 'name_last_formatted' => $person['last_name'], 'name_last_metaphone' => metaphone(PSU::stripPunct($person['last_name'])), 'name_middle_formatted' => $person['middle_name'], 'name_full' => trim(preg_replace('/\\s\\s+/', ' ', $person['first_name'] . ' ' . substr($person['middle_name'], 0, 1) . ' ' . $person['last_name'] . ' ' . $person['spbpers_name_suffix'])), 'phone_of' => $person['office_phone'] ? '(603) ' . substr($person['office_phone'], 0, 3) . '-' . substr($person['office_phone'], 3) : FALSE, 'phone_vm' => $person['phone_number'] ? '(603) ' . substr($person['phone_number'], 0, 3) . '-' . substr($person['phone_number'], 3) : FALSE, 'emp' => $person['emp'] ? 1 : 0, 'stu' => $person['stu'] ? 1 : 0, 'stu_account' => $person['stu_account'] ? 1 : 0, 'dept' => $person['department'] ?: '', 'title' => $person['title'] ?: '', 'major' => $person['major'] ?: '', 'has_idcard' => $person['has_idcard']);
    return $final;
}
function customize()
{
    print metaphone("That's just wack");
    $fields = array();
    $fields["heading_1"] = COMP_NAME;
    $fields["heading_2"] = date("d/m/Y");
    $fields["heading_3"] = "Balance Sheet";
    $fields["heading_4"] = "Prepared by: " . USER_NAME;
    foreach ($fields as $var_name => $value) {
        ${$var_name} = $value;
    }
    db_conn("cubit");
    $OUTPUT = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>\n\t\t<tr>\n\t\t\t<td align='left'><h3>{$heading_1}</h3></td>\n\t\t\t<td align='right'><h3>{$heading_2}</h3></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align='left'><h3>{$heading_3}</h3></td>\n\t\t\t<td align='right'><h3>{$heading_4}</h3></td>\n\t\t</tr>\n\t</table>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr>\n\t\t\t<th>";
    return $OUTPUT;
}
Example #12
0
 /**
  * Get web wervice polyline parameter being decoded
  * @param $rsp - string 
  * @param string $param - response key
  * @return string - JSON
  */
 protected function decode($rsp, $param = 'routes.overview_polyline.points')
 {
     $needle = metaphone($param);
     // get response
     $obj = json_decode($rsp, true);
     // flatten array into single level array using 'dot' notation
     $obj_dot = array_dot($obj);
     // create empty response
     $response = [];
     // iterate
     foreach ($obj_dot as $key => $val) {
         // Calculate the metaphone key and compare with needle
         $val = strcmp(metaphone($key, strlen($needle)), $needle) === 0 ? PolyUtil::decode($val) : $val;
         array_set($response, $key, $val);
     }
     return json_encode($response, JSON_PRETTY_PRINT);
 }
 public function findPhonetically($productName)
 {
     $productNameMeta = metaphone($productName);
     $map = [];
     $max = SIMILAR_MIN_THRESHOLD;
     $productId = 0;
     $products = Product::scope()->with('default_tax_rate')->get();
     foreach ($products as $product) {
         if (!$product->product_key) {
             continue;
         }
         $map[$product->id] = $product;
         $similar = similar_text($productNameMeta, metaphone($product->product_key), $percent);
         if ($percent > $max) {
             $productId = $product->id;
             $max = $percent;
         }
     }
     return $productId && isset($map[$productId]) ? $map[$productId] : null;
 }
Example #14
0
function getMetaphoneM($first, $second, $result)
{
    $arFirst = explode(" ", $first);
    $arSecond = explode(" ", $second);
    $m1 = $m2 = "";
    foreach ($arFirst as $val) {
        $m1 .= metaphone($val);
    }
    foreach ($arSecond as $val2) {
        $m2 .= metaphone($val2);
    }
    $metaphone['levenshtein'] = levenshtein($m1, $m2);
    $metaphone['similarity'] = similar_text($m1, $m2, $perc);
    $metaphone['percentage'] = $perc;
    if ($result['levenshtein'] > $metaphone['levenshtein'] && $result['percentage'] <= $metaphone['percentage']) {
        $result["levenshtein"] = $metaphone['levenshtein'];
        $result["percentage"] = $metaphone['percentage'];
        $result["match"] = $second;
    }
    return $result;
}
Example #15
0
function pleac_Soundex_Matching()
{
    #-----------------------------
    $code = soundex($string);
    #-----------------------------
    $phoned_words = metaphone("Schwern");
    #-----------------------------
    // substitution function for getpwent():
    // returns an array of user entries,
    // each entry contains the username and the full name
    function getpwent()
    {
        $pwents = array();
        $handle = fopen("passwd", "r");
        while (!feof($handle)) {
            $line = fgets($handle);
            if (preg_match("/^#/", $line)) {
                continue;
            }
            $cols = explode(":", $line);
            $pwents[$cols[0]] = $cols[4];
        }
        return $pwents;
    }
    print "Lookup user: "******"/(\\w+)[^,]*\\b(\\w+)/", $fullname, $matches);
        list(, $firstname, $lastname) = $matches;
        if ($name_code == soundex($username) || $name_code == soundex($lastname) || $name_code == soundex($firstname)) {
            printf("%s: %s %s\n", $username, $firstname, $lastname);
        }
    }
    #-----------------------------
}
 /**
  * Generates a string of environment information and
  * takes the hash of that value to use as the env
  * fingerprint.
  *
  * @return string
  */
 public static final function generate()
 {
     if (null !== self::$finHash) {
         return self::$finHash;
     }
     self::$finHash = '';
     self::$sigData = array();
     $serverVariables = array('server_software', 'server_name', 'server_addr', 'server_port', 'document_root');
     foreach ($_SERVER as $k => $v) {
         if (in_array(strtolower($k), $serverVariables)) {
             self::$sigData[] = $v;
         }
     }
     self::$sigData[] = phpversion();
     self::$sigData[] = get_current_user();
     self::$sigData[] = php_uname('s') . php_uname('n') . php_uname('m') . PHP_OS . PHP_SAPI . ICONV_IMPL . ICONV_VERSION;
     self::$sigData[] = sha1_file(__FILE__);
     self::$finHash = implode(self::$sigData);
     self::$finHash = sha1(str_ireplace(' ', '', self::$finHash) . strlen(self::$finHash) . metaphone(self::$finHash));
     self::$finHash = sha1(self::$finHash);
     return self::$finHash;
 }
function get_matches($rq)
{
    global $magnatune;
    $tracks = @$magnatune[metaphone($rq->artist)][metaphone($rq->track)];
    if (!$tracks) {
        return array();
    }
    $ret = array();
    foreach ($tracks as $t) {
        $pi = new stdclass();
        $pi->artist = $t['artist'];
        $pi->track = $t['track'];
        $pi->album = $t['album'];
        $pi->source = "Magnatune.com";
        //      $pi->size   = 0;
        $pi->bitrate = 128;
        $pi->duration = (int) $t['duration'];
        $pi->url = $t['url'];
        $pi->score = (double) 1.0;
        $ret[] = $pi;
    }
    return $ret;
}
Example #18
0
 /**
  * Tries to find the most similar name
  *
  * @param string $methodName
  * @return string|boolean
  */
 public function getPossibleMethodName($methodName)
 {
     $methodNameLower = strtolower($methodName);
     foreach ($this->methods as $name => $method) {
         if (metaphone($methodNameLower) == metaphone($name)) {
             return $method->getName();
         }
     }
     $extendsClassDefinition = $this->extendsClassDefinition;
     if ($extendsClassDefinition) {
         return $extendsClassDefinition->getPossibleMethodName($methodName);
     }
     return false;
 }
Example #19
0
function pfind_interpret($entries, $mode, &$waypoints, $path, $node_types)
{
    global $wpdb;
    $result = array();
    $result['error'] = 200;
    //start optimistically
    $result['error_str'] = 'no errors';
    $waypoints = array();
    if (clb_count($entries) <= 0) {
        $result['error'] = 400;
        $result['error_str'] = 'no locations received to parse';
        return $result;
    }
    //if only one entry we expect a a "to" separating origin and dest
    if (count($entries) == 1) {
        $entries = preg_split('/\\s+to\\s+/i', trim(reset($entries)), -1, PREG_SPLIT_NO_EMPTY);
    }
    if (clb_count($entries) == 1) {
        $result['error'] = 400;
        $result['error_str'] = 'only one location';
        return $result;
    }
    if (is_file($path)) {
        $path = dirname($path);
    }
    $path = clb_dir($path) . 'metaphones.txt';
    //like spelling city
    $index = FALSE;
    if (is_file($path)) {
        $data = file_get_contents($path);
        //, FILE_BINARY);
        $index = clb_blob_dec($data);
    }
    $pickone = array();
    foreach ($entries as $loc) {
        $loc = strtolower($loc);
        $sel = FALSE;
        $select = 'SELECT ' . RF_NODES_SELECT . ' FROM ' . RF_NODES_FROM . ' ';
        //'SELECT pnum, ptype, title, more, lat, lng FROM places ';
        $where = ' WHERE ';
        //the list of ptypes that will be used to limit the names search
        $ptypes = $node_types;
        //if more than one mode check if the user has added clarifying name to the name eg "oxford rail"
        if (count($ptypes) > 1) {
            foreach ($ptypes as $type) {
                if (clb_contains($loc, $type)) {
                    //allow the user to force a mode, by adding the code to the name
                    $ptypes = array($type);
                    //replace all other modes
                    $loc = trim(preg_replace('/\\s*\\b' . preg_quote($type) . '\\b\\s*/i', ' ', $loc));
                    //remove the signal from the name
                }
            }
        }
        //get rid of quotes and escapes
        $loc = trim(str_replace(array('\\', '"'), ' ', $loc));
        if (preg_match('/^\\s*(-?[\\.\\d]+)\\s*,\\s*(-?[\\.\\d]+)\\s*$/', $loc, $m)) {
            //waypoint given as lat/lng pair
            //limit search by node types
            if (clb_count($ptypes)) {
                $where .= ' ' . RF_NODES_TYPE . ' IN ' . clb_join($ptypes, TRUE) . ' AND ';
            }
            list($junk, $lat, $lng) = $m;
            for ($dist = 200; $dist <= 500; $dist += 100) {
                $sel = $wpdb->get_results($select . $where . within_rect($lat, $lng, $dist), ARRAY_A);
                $sel = clb_rekey($sel, RF_NODES_KEY);
                if (clb_count($sel) > 1) {
                    break;
                }
            }
            if (clb_count($sel) <= 0) {
                $result = array('error' => 602, 'error_str' => 'no tranpost node could be found near coordinates ' . $lat . ', ' . $lng);
                return $result;
            }
        } else {
            if (preg_match('/^node:\\s*(\\w+)\\s*$/', $loc, $m)) {
                //waypoint specified by pnum
                $sel = $wpdb->get_results($select . ' WHERE ' . RF_NODES_KEY . '=' . clb_escape($m[1]), ARRAY_A);
                $sel = clb_rekey($sel, RF_NODES_KEY);
            } else {
                if (in_array('rail', $ptypes) && preg_match('/^\\s*(\\w{3})\\s*$/', $loc, $m)) {
                    //rail station three letter code
                    $sel = $wpdb->get_results($select . ' WHERE ' . RF_NODES_TYPE . '="rail" AND (extref=' . clb_escape($m[1]) . ' OR ' . RF_NODES_NAME . '=' . clb_escape($m[1]) . ')', ARRAY_A);
                    $sel = clb_rekey($sel, RF_NODES_KEY);
                } else {
                    /*
                    	the primary key of the sound index structrue is the metaphone.  Inside that are ptypes using that saound.
                    	within each ptype there is a list of specific pnums using that sound in the name.
                    	on each first word, get all pnums for that sound and type, on subsequent words intesect with pnums
                    	so that we end up with pnums which have all sounds.
                    	$index[$sound][ptype][] => pnum
                    */
                    $sel = FALSE;
                    $name = pfind_unify_names($loc);
                    if (is_array($index)) {
                        $intersection = FALSE;
                        $words = preg_split('/\\W+/', $name, -1, PREG_SPLIT_NO_EMPTY);
                        foreach ($words as $w) {
                            if ($w == '&') {
                                $w = 'and';
                            }
                            $sound = metaphone($w);
                            if ($sound && isset($index[$sound])) {
                                $set = array();
                                foreach ($index[$sound] as $ptype => $nodes) {
                                    if (in_array($ptype, $ptypes)) {
                                        $set = array_merge($set, $nodes);
                                    }
                                }
                                $intersection = !is_array($intersection) ? $set : array_intersect($set, $intersection);
                            }
                        }
                        if (clb_count($intersection)) {
                            $query = $select . $where . ' ' . RF_NODES_KEY . ' IN ' . clb_join($intersection, TRUE);
                            $sel = $wpdb->get_results($query, ARRAY_A);
                            $sel = clb_rekey($sel, RF_NODES_KEY);
                        }
                    } else {
                        $query = $select . $where . ' ' . RF_NODES_NAME . ' LIKE ' . clb_escape($name . '%');
                        if (clb_count($ptypes)) {
                            $query .= ' AND ' . RF_NODES_TYPE . ' IN ' . clb_join($ptypes, TRUE);
                        }
                        $sel = $wpdb->get_results($query, ARRAY_A);
                        $sel = clb_rekey($sel, RF_NODES_KEY);
                    }
                    //if more than one match scan for common words and remove the matches if they did not contain them
                    if (clb_count($sel) > 1) {
                        foreach ($sel as $i => $row) {
                            //exact match go for it alone
                            if (strtolower($row[RF_NODES_NAME]) == strtolower($loc)) {
                                $sel = array($i => $row);
                                break;
                            }
                            //if the full name contains "road" but the requested name does not
                            //omit this choice to avoid stations like "london road" when looking for london
                            if (preg_match('/\\b(road)\\b/i', $row[RF_NODES_NAME], $m)) {
                                if (!clb_contains($loc, $m[1], FALSE)) {
                                    unset($sel[$i]);
                                }
                            }
                        }
                    }
                }
            }
        }
        if (clb_count($sel) <= 0) {
            $result = array('error' => 602, 'error_str' => 'no stations with the name ' . $loc);
            return $result;
        }
        $waypoints[] = $sel;
    }
    return $result;
}
Example #20
0
 /**
  * Compares string1 with string2 using php's string phonetics functions.
  *  This function takes into account how the strings "sound" when they are
  *  pronounced, and it considers phrases with similar initial phonetics
  *  to be of greater similarity than those without similar initial phonetics
  *
  * Currently (2011-07-29) this function normalizes to the english
  *  pronunciation patterns of words; other patterns, like spanish, are
  *  not supported.
  *
  * This function is similar to phoneticSimilarity() except that it uses
  *  the weighted similarity functionality from weightedSimilarity() to
  *  correlate phrases with similar beginnings.
  *
  * Note that this function, like weightedSimilarity() defaults to  
  *  unidirectional mode, meaning that the order of the string arguments 
  *  matters. Keep in mind that a short string compared against a long 
  *  string can yield a 100% match, and will disregard the tail of the 
  *  longer string.
  *
  * @param string $string1
  *  The base string we are comparing against.
  * @param string $string2
  *  The test string that we wish to verify.
  * @param int $gradient
  *  See weightedSimilarity()
  * @return The percentage of phonetic correlation between the two strings.
  *  (ie: complete phonetic match = 100, complete phonetic mis-match = 0)
  * @author David Hazel
  **/
 public function weightedPhoneticSimilarity($string1, $string2, $gradient = 0)
 {
     // check for bidirection
     if (!empty($this->biDirectional)) {
         // set string1 to be the longest string of the two
         if (strlen($string1) < strlen($string2)) {
             $tmp = $string1;
             $string1 = $string2;
             $string2 = $tmp;
             unset($tmp);
         }
     }
     // generate the metaphone code for each string
     $metaphone1 = metaphone($string1);
     $metaphone2 = metaphone($string2);
     // calculate and return the normalized similarity between the codes
     return $this->weightedSimilarity($metaphone1, $metaphone2, $gradient);
 }
    $res = mysql_query("select rec_ID, rec_RecTypeID, rec_Title, dtl_Value from Records left join recDetails on dtl_RecID=rec_ID and dtl_DetailTypeID={$titleDT} where " . (strlen($recIDs) > 0 ? "rec_ID in ({$recIDs}) and " : "") . "rec_RecTypeID != {$relRT} and not rec_FlagTemporary order by rec_RecTypeID desc");
}
$rectypes = mysql__select_assoc('defRecTypes', 'rty_ID', 'rty_Name', '1');
while ($row = mysql_fetch_assoc($res)) {
    if ($personMatch) {
        if ($row['dtl_Value']) {
            $val = $row['dtl_Value'] . ($recsGivenNames[$row['rec_ID']] ? " " . $recsGivenNames[$row['rec_ID']] : "");
        }
    } else {
        if ($row['rec_Title']) {
            $val = $row['rec_Title'];
        } else {
            $val = $row['dtl_Value'];
        }
    }
    $mval = metaphone(preg_replace('/^(?:a|an|the|la|il|le|die|i|les|un|der|gli|das|zur|una|ein|eine|lo|une)\\s+|^l\'\\b/i', '', $val));
    if ($crosstype || $personMatch) {
        //for crosstype or person matching leave off the type ID
        $key = '' . substr($mval, 0, $fuzziness);
    } else {
        $key = $row['rec_RecTypeID'] . '.' . substr($mval, 0, $fuzziness);
    }
    $typekey = $rectypes[$row['rec_RecTypeID']];
    if (!array_key_exists($key, $bibs)) {
        $bibs[$key] = array();
    } else {
        // it's a dupe so process it
        if (!array_key_exists($typekey, $dupes)) {
            $dupes[$typekey] = array();
        }
        if (!array_key_exists($key, $dupekeys)) {
Example #22
0
 /**
  * Write the image after being processed
  *
  * @param Asido_TMP &$tmp
  * @return boolean
  * @access protected
  */
 function __write(&$tmp)
 {
     // try to guess format from extension
     //
     if (!$tmp->save) {
         $p = pathinfo($tmp->target_filename);
         ($tmp->save = $this->__mime_metaphone[metaphone($p['extension'])]) || ($tmp->save = $this->__mime_soundex[soundex($p['extension'])]);
     }
     $result = false;
     $imgContent = null;
     switch ($tmp->save) {
         case 'image/gif':
             imageTrueColorToPalette($tmp->target, true, 256);
             ob_start();
             $result = @imageGIF($tmp->target);
             $imgContent = ob_get_clean();
             break;
         case 'image/jpeg':
             ob_start();
             $result = @imageJPEG($tmp->target, null, ASIDO_GD_JPEG_QUALITY);
             $imgContent = ob_get_clean();
             break;
         case 'image/wbmp':
             ob_start();
             $result = @imageWBMP($tmp->target);
             $imgContent = ob_get_clean();
             break;
         default:
         case 'image/png':
             imageSaveAlpha($tmp->target, true);
             imageAlphaBlending($tmp->target, false);
             ob_start();
             $result = @imagePNG($tmp->target, null, ASIDO_GD_PNG_QUALITY);
             $imgContent = ob_get_clean();
             break;
     }
     if ($result) {
         jimport('joomla.filesystem.file');
         JFile::write($tmp->target_filename, $imgContent);
     }
     @$this->__destroy_source($tmp);
     @$this->__destroy_target($tmp);
     return $result;
 }
Example #23
0
 /**
  * Creating metaphone based hash from input word
  *
  * @param string $word Word to convert
  * @param bool $returnRawMetaphoneValue If set, returns the raw metaphone value (not hashed)
  * @return mixed Metaphone hash integer (or raw value, string)
  */
 public function metaphone($word, $returnRawMetaphoneValue = false)
 {
     if (is_object($this->metaphoneObj)) {
         $metaphoneRawValue = $this->metaphoneObj->metaphone($word, $this->conf['sys_language_uid']);
     } else {
         // Use native PHP function instead of advanced doubleMetaphone class
         $metaphoneRawValue = metaphone($word);
     }
     if ($returnRawMetaphoneValue) {
         $result = $metaphoneRawValue;
     } elseif ($metaphoneRawValue !== '') {
         // Create hash and return integer
         $result = IndexedSearchUtility::md5inthash($metaphoneRawValue);
     } else {
         $result = 0;
     }
     return $result;
 }
Example #24
0
 /** 
  * Executes the search.
  * 
  * @param string $_search
  * 
  * @return array
  */
 function search($_search)
 {
     $startTime = microtime(true);
     $this->searchString = trim(stripslashes($_search));
     $keywordCount = $this->parseSearchString($this->searchString);
     if (empty($this->searchString) or empty($this->searchArray)) {
         return array('count' => 0, 'hits' => array(), 'keywords' => array(), 'keywords' => '', 'sql' => 'No search performed.', 'blacklisted' => false, 'hash' => '', 'simwordsnewsearch' => '', 'simwords' => array(), 'time' => 0);
     }
     // ask cache
     if ($this->cache and $this->isCached($this->searchString)) {
         $this->cachedArray['time'] = microtime(true) - $startTime;
         if ($this->similarwords and $this->cachedArray['count'] > 0) {
             $this->storeKeywords($this->searchArray);
         }
         // EP registrieren
         rex_register_extension_point('A587_SEARCH_EXECUTED', $this->cachedArray);
         //var_dump($this->cachedArray['sql']);
         return $this->cachedArray;
     }
     $return = array();
     $return['simwordsnewsearch'] = '';
     $return['simwords'] = array();
     if ($this->similarwords) {
         $simwords = array();
         foreach ($this->searchArray as $keyword) {
             $sounds = array();
             if ($this->similarwordsMode & A587_SIMILARWORDS_SOUNDEX) {
                 $sounds[] = "soundex = '" . soundex($keyword['search']) . "'";
             }
             if ($this->similarwordsMode & A587_SIMILARWORDS_METAPHONE) {
                 $sounds[] = "metaphone = '" . metaphone($keyword['search']) . "'";
             }
             if ($this->similarwordsMode & A587_SIMILARWORDS_COLOGNEPHONE) {
                 $sounds[] = "colognephone = '" . $this->cologne_phone($keyword['search']) . "'";
             }
             $simwords[] = sprintf("\n          SELECT\n            GROUP_CONCAT(DISTINCT keyword SEPARATOR ' ') as keyword,\n            '%s' AS typedin,\n            SUM(count) as count\n          FROM `%s`\n          WHERE 1\n            %s\n            AND (%s)", $keyword['search'], $this->tablePrefix . '587_keywords', $this->clang !== false ? 'AND (clang = ' . intval($this->clang) . ' OR clang IS NULL)' : '', implode(' OR ', $sounds));
         }
         // simwords
         $simWordsSQL = new rex_sql();
         foreach ($simWordsSQL->getArray(sprintf("\n        %s\n        GROUP BY %s\n        ORDER BY SUM(count)", implode(' UNION ', $simwords), $this->similarwordsPermanent ? "''" : 'keyword, typedin')) as $simword) {
             $return['simwords'][$simword['typedin']] = array('keyword' => $simword['keyword'], 'typedin' => $simword['typedin'], 'count' => $simword['count']);
         }
         $newsearch = array();
         foreach ($this->searchArray as $keyword) {
             if (preg_match($this->encodeRegex('~\\s~is'), $keyword['search'])) {
                 $quotes = '"';
             } else {
                 $quotes = '';
             }
             if (array_key_exists($keyword['search'], $return['simwords'])) {
                 $newsearch[] = $quotes . $return['simwords'][$keyword['search']]['keyword'] . $quotes;
             } else {
                 $newsearch[] = $quotes . $keyword['search'] . $quotes;
             }
         }
         $return['simwordsnewsearch'] = implode(' ', $newsearch);
     }
     if ($this->similarwordsPermanent) {
         $keywordCount = $this->parseSearchString($this->searchString . ' ' . $return['simwordsnewsearch']);
     }
     $searchColumns = array();
     switch ($this->textMode) {
         case 'unmodified':
             $searchColumns[] = 'unchangedtext';
             break;
         case 'both':
             $searchColumns[] = 'plaintext';
             $searchColumns[] = 'unchangedtext';
             break;
         default:
             $searchColumns[] = 'plaintext';
     }
     $sql = new rex_sql();
     $Awhere = array();
     $Amatch = array();
     foreach ($this->searchArray as $keyword) {
         // build MATCH-Array
         $match = sprintf("(( MATCH (`%s`) AGAINST ('%s')) * %d)", implode('`,`', $searchColumns), $sql->escape($keyword['search']), $keyword['weight']);
         if ($this->searchEntities) {
             $match .= ' + ' . sprintf("(( MATCH (`%s`) AGAINST ('%s')) * %d)", implode('`,`', $searchColumns), $sql->escape(htmlentities($keyword['search'], ENT_COMPAT, 'UTF-8')), $keyword['weight']);
         }
         $Amatch[] = $match;
         // build WHERE-Array
         if ($this->searchMode == 'match') {
             $AWhere[] = $match;
         } else {
             $tmpWhere = array();
             foreach ($searchColumns as $searchColumn) {
                 $tmpWhere[] = sprintf("(`%s` LIKE '%%%s%%')", $searchColumn, str_replace(array('%', '_'), array('\\%', '\\_'), $sql->escape($keyword['search'])));
                 if ($this->searchEntities) {
                     $tmpWhere[] = sprintf("(`%s` LIKE '%%%s%%')", $searchColumn, str_replace(array('%', '_'), array('\\%', '\\_'), $sql->escape(htmlentities($keyword['search'], ENT_COMPAT, 'UTF-8'))));
                 }
             }
             $AWhere[] = '(' . implode(' OR ', $tmpWhere) . ')';
         }
         /*if($this->logicalMode == ' AND ')
             $Awhere[] = '+*'.$keyword['search'].'*';
           else
             $AWhere[] = '*'.$keyword['search'].'*';*/
     }
     // build MATCH-String
     $match = '(' . implode(' + ', $Amatch) . ' + 1)';
     // build WHERE-String
     $where = '(' . implode($this->logicalMode, $AWhere) . ')';
     #$where = sprintf("( MATCH (%s) AGAINST ('%s' IN BOOLEAN MODE)) > 0",implode(',',$searchColumns),implode(' ',$Awhere));
     // language
     if ($this->clang !== false) {
         $where .= ' AND (clang = ' . intval($this->clang) . ' OR clang IS NULL)';
     }
     $AwhereToSearch = array();
     if (array_key_exists('articles', $this->searchInIDs) and count($this->searchInIDs['articles'])) {
         $AwhereToSearch[] = "texttype = 'article'";
         $AwhereToSearch[] = "(fid IN (" . implode(',', $this->searchInIDs['articles']) . "))";
     }
     if (array_key_exists('categories', $this->searchInIDs) and count($this->searchInIDs['categories'])) {
         $AwhereToSearch[] = "(catid IN (" . implode(',', $this->searchInIDs['categories']) . ") AND ftable = '" . $sql->escape($this->tablePrefix) . "article')";
     }
     if (array_key_exists('filecategories', $this->searchInIDs) and count($this->searchInIDs['filecategories'])) {
         $AwhereToSearch[] = "(catid IN (" . implode(',', $this->searchInIDs['filecategories']) . ") AND ftable = '" . $sql->escape($this->tablePrefix) . "file')";
     }
     if (array_key_exists('db_columns', $this->searchInIDs) and count($this->searchInIDs['db_columns'])) {
         $AwhereToSearch[] = "texttype = 'db_column'";
         $Acolumns = array();
         foreach ($this->searchInIDs['db_columns'] as $table => $colArray) {
             foreach ($colArray as $column) {
                 //$Acolumns[] = sprintf("(ftable = '%s' AND fcolumn = '%s' %s)", $table, $column, $strSearchArticles);
                 $Acolumns[] = sprintf("(ftable = '%s' AND fcolumn = '%s')", $table, $column);
             }
         }
         $AwhereToSearch[] = '(' . implode(' OR ', $Acolumns) . ')';
     }
     if (count($AwhereToSearch)) {
         if ($this->searchArticles) {
             $where .= " AND ((texttype = 'article') OR (" . implode(' AND ', $AwhereToSearch) . '))';
         } else {
             $where .= ' AND (' . implode(' AND ', $AwhereToSearch) . ')';
         }
     }
     if (!empty($this->where)) {
         $where .= ' AND (' . $this->where . ')';
     }
     // build ORDER-BY-String
     $Aorder = array();
     foreach ($this->order as $col => $dir) {
         $Aorder[] = $col . ' ' . $dir;
     }
     $selectFields = array();
     if ($this->groupBy) {
         $selectFields[] = sprintf('(SELECT SUM%s FROM `%s` summe WHERE summe.fid = r1.fid AND summe.ftable = r1.ftable) AS RELEVANCE587', $match, $this->tablePrefix . '587_searchindex');
         $selectFields[] = sprintf('(SELECT COUNT(*) FROM `%s` summe WHERE summe.fid = r1.fid AND (summe.ftable IS NULL OR summe.ftable = r1.ftable) AND (summe.fcolumn IS NULL OR summe.fcolumn = r1.fcolumn) AND summe.texttype = r1.texttype) AS COUNT587', $this->tablePrefix . '587_searchindex');
     } else {
         $selectFields[] = $match . ' AS RELEVANCE587';
     }
     $selectFields[] = '`id`';
     $selectFields[] = '`fid`';
     $selectFields[] = '`catid`';
     $selectFields[] = '`ftable`';
     $selectFields[] = '`fcolumn`';
     $selectFields[] = '`texttype`';
     $selectFields[] = '`clang`';
     $selectFields[] = '`unchangedtext`';
     $selectFields[] = '`plaintext`';
     $selectFields[] = '`teaser`';
     $selectFields[] = '`values`';
     $selectFields[] = '`filename`';
     $selectFields[] = '`fileext`';
     if ($this->groupBy) {
         $query = sprintf('
     SELECT SQL_CALC_FOUND_ROWS %s
     FROM `%s` r1
     WHERE (%s) AND (
       (
         %s = (SELECT MAX%s FROM `%s` r2 WHERE r1.ftable = r2.ftable AND r1.fid = r2.fid %s)
         AND fid IS NOT NULL
       ) OR
       ftable IS NULL
     )
     GROUP BY ftable,fid,clang
     ORDER BY %s
     LIMIT %d,%d', implode(",\n", $selectFields), $this->tablePrefix . '587_searchindex', $where, $match, $match, $this->tablePrefix . '587_searchindex', $this->clang !== false ? 'AND (clang = ' . intval($this->clang) . ' OR clang IS NULL)' : '', implode(",\n", $Aorder), $this->limit[0], $this->limit[1]);
     } else {
         $query = sprintf('
     SELECT SQL_CALC_FOUND_ROWS %s
     FROM `%s`
     WHERE %s
     ORDER BY %s
     LIMIT %d,%d', implode(",\n", $selectFields), $this->tablePrefix . '587_searchindex', $where, implode(",\n", $Aorder), $this->limit[0], $this->limit[1]);
     }
     #echo '<pre>'.$query.'</pre>';
     $sqlResult = $sql->getArray($query);
     $indexIds = array();
     $count = 0;
     $sqlResultCount = $sql->getArray('SELECT FOUND_ROWS() as count');
     $return['count'] = intval($sqlResultCount[0]['count']);
     // hits
     $return['hits'] = array();
     $i = 0;
     foreach ($sqlResult as $hit) {
         $indexIds[] = $hit['id'];
         $return['hits'][$i] = array();
         $return['hits'][$i]['id'] = $hit['id'];
         $return['hits'][$i]['fid'] = $hit['fid'];
         if (!is_numeric($hit['fid']) and !is_null($json_decode_fid = json_decode($hit['fid'], true))) {
             $return['hits'][$i]['fid'] = $json_decode_fid;
         }
         $return['hits'][$i]['table'] = $hit['ftable'];
         $return['hits'][$i]['column'] = $hit['fcolumn'];
         $return['hits'][$i]['type'] = $hit['texttype'];
         $return['hits'][$i]['clang'] = $hit['clang'];
         $return['hits'][$i]['unchangedtext'] = $hit['unchangedtext'];
         $return['hits'][$i]['plaintext'] = $hit['plaintext'];
         $return['hits'][$i]['teaser'] = $this->getTeaserText($hit['plaintext']);
         $return['hits'][$i]['highlightedtext'] = $this->getHighlightedText($hit['plaintext']);
         $return['hits'][$i]['article_teaser'] = $hit['teaser'];
         $return['hits'][$i]['values'] = a587_config_unserialize($hit['values']);
         $return['hits'][$i]['filename'] = $hit['filename'];
         $return['hits'][$i]['fileext'] = $hit['fileext'];
         $i++;
         if ($this->groupBy) {
             $count += $hit['COUNT587'];
         }
     }
     if ($this->groupBy) {
         $indexIds = array();
         foreach ($sql->getArray(sprintf('
         SELECT id
         FROM `%s`
         WHERE %s
         LIMIT %d,%d', $this->tablePrefix . '587_searchindex', $where, $this->limit[0], $count)) as $hit) {
             $indexIds[] = $hit['id'];
         }
     }
     // keywords, which were searched for
     $return['keywords'] = $this->searchArray;
     $return['searchterm'] = $this->searchString;
     // sql
     $return['sql'] = $query;
     // was any blacklisted word searched for?
     $return['blacklisted'] = false;
     if (count($this->blacklisted) > 0) {
         $return['blacklisted'] = $this->blacklisted;
     }
     $return['hash'] = $this->cacheHash($this->searchString);
     if ($this->similarwords and $i) {
         $this->storeKeywords($this->searchArray);
     }
     if ($this->cache) {
         $this->cacheSearch(serialize($return), $indexIds);
     }
     // EP registrieren
     rex_register_extension_point('A587_SEARCH_EXECUTED', $return);
     $return['time'] = microtime(true) - $startTime;
     return $return;
 }
Example #25
0
function kpg_find_permalink_post_metaphone($plink, $find, $kpg_pf_numbs, $kpg_pf_common, $kpg_pf_short)
{
    global $wpdb;
    // useful db functions
    // common word list - these tend to skew results so don't use them
    $common = "  am an and at be but by did does had has her him his its may she than that the them then there these they ";
    global $wpdb;
    // useful db functions
    // common word list - these tend to skew results so don't use them
    $common = "  am an and at be but by did does had has her him his its may she than that the them then there these they ";
    $ss1 = explode("-", $plink);
    // place into an arrary
    $ss = array();
    // look for each word in the array. If found add in 1; if not add in 0. Order by sum and the best bet bubbles to top.
    // remove the numbers and small words from $ss1
    foreach ($ss1 as $se) {
        if (!empty($se)) {
            if ($kpg_pf_numbs == 'Y' && is_numeric($se)) {
                // ignore this guy - he's numeric
            } else {
                if ($kpg_pf_common == 'Y' && strpos(' ' . $common . ' ', $se) !== false) {
                    // ignore because of a common word
                } else {
                    if ($kpg_pf_short == 'Y' && strlen($se) < 3) {
                        // ignore the word it is too short
                    } else {
                        // use this word
                        $ss[count($ss)] = $se;
                    }
                }
            }
        }
    }
    $findcnt = $find;
    if ($find > count($ss)) {
        $findcnt = count($ss);
    }
    if (empty($ss)) {
        return array(false, 0);
    }
    // we need to do the search but do a metaphone  search on each word
    $ss1 = $ss;
    $ss = array();
    foreach ($ss1 as $se) {
        if (strlen(metaphone($se)) > 1) {
            $ss[] = metaphone($se);
        }
    }
    $findcnt = $find;
    if ($find > count($ss)) {
        $findcnt = count($ss);
    }
    if (empty($ss)) {
        return array(false, 0);
    }
    $sql = "SELECT ID,post_name as PN FROM " . $wpdb->posts . " WHERE post_status = 'publish' \n\tand POST_TYPE <> 'attachment' and POST_TYPE <> 'nav_menu_item' \n\tORDER BY post_modified DESC";
    $rows = $wpdb->get_results($sql, ARRAY_A);
    $ansa = array();
    foreach ($rows as $row) {
        extract($row);
        $PN = str_replace(' ', '-', $PN);
        // just for the hell of it
        $PN = str_replace('_', '-', $PN);
        $st = explode('-', $PN);
        $CNT = 0;
        if (!empty($st) && count($st) >= $findcnt) {
            foreach ($st as $sst) {
                $se = metaphone($sst);
                if (strlen($se) > 1) {
                    if (in_array($se, $ss)) {
                        $CNT++;
                    }
                }
            }
            if ($CNT >= $findcnt) {
                $ansa[$ID] = $CNT;
            }
        }
    }
    if (empty($ansa)) {
        return array(false, 0);
    }
    // sort array by CNT keeping keys
    arsort($ansa);
    foreach ($ansa as $ID => $CNT) {
        if ($CNT >= $findcnt) {
            return array($ID, $CNT);
        }
        // we were getting zero counts somehow
    }
    return array(false, 0);
}
function checkWithCity($searchCity)
{
    global $total_return;
    $arData = array();
    //array to hold all details
    $arCity["1"] = "Abia";
    $arCity["2"] = "Abuja";
    $arCity["3"] = "Adamawa";
    $arCity["4"] = "Akwa Ibom";
    $arCity["5"] = "Anambra";
    $arCity["6"] = "Bauchi";
    $arCity["7"] = "Bayelsa";
    $arCity["8"] = "Benue";
    $arCity["9"] = "Borno";
    $arCity["10"] = "Cross River";
    $arCity["11"] = "Delta";
    $arCity["12"] = "Ebonyi";
    $arCity["13"] = "Edo";
    $arCity["14"] = "Ekiti";
    $arCity["15"] = "Enugu";
    $arCity["16"] = "Gombe";
    $arCity["53"] = "Gongola";
    $arCity["17"] = "Imo";
    $arCity["18"] = "Jigawa";
    $arCity["19"] = "Kaduna";
    $arCity["20"] = "Kano";
    $arCity["21"] = "Katsina";
    $arCity["22"] = "Kebbi";
    $arCity["23"] = "Kogi";
    $arCity["24"] = "Kwara";
    $arCity["25"] = "Lagos";
    $arCity["26"] = "Nassarawa";
    $arCity["27"] = "Niger";
    $arCity["28"] = "Ogun";
    $arCity["29"] = "Ondo";
    $arCity["30"] = "Osun";
    $arCity["40"] = "Others - Africa";
    $arCity["39"] = "Others - Asia";
    $arCity["43"] = "Others - Caribbean";
    $arCity["48"] = "Others - Central America";
    $arCity["38"] = "Others - Europe";
    $arCity["44"] = "Others - Middle East";
    $arCity["41"] = "Others - North America";
    $arCity["47"] = "Others - Not Listed";
    $arCity["45"] = "Others - Oceania";
    $arCity["42"] = "Others - South America";
    $arCity["31"] = "Oyo";
    $arCity["32"] = "Plateau";
    $arCity["54"] = "River";
    $arCity["33"] = "Rivers";
    $arCity["34"] = "Sokoto";
    $arCity["35"] = "Taraba";
    $arCity["36"] = "Yobe";
    $arCity["37"] = "Zamfara";
    //seraching for available cities
    $myCityID = '';
    $skey = 'restaurant';
    //fixed search what
    $return = '';
    //return from CURL
    echo 'inside City<br>';
    foreach ($arCity as $cityID => $cityName) {
        if (metaphone($searchCity, 5) == metaphone($cityName, 5)) {
            $myCityID = $cityID;
            break;
        }
    }
    echo "{$myCityID} city id<br>";
    if ($myCityID) {
        echo 'City id found<br>';
        $index = 0;
        //$return = curlPOST($loc, $myCityID);
        /* echo $url = "http://nigerianyellowpages.com/search-name_g.php";
           $fields_string = "location=$myCityID&skey=$skey&submit=Search";
           $ch = curl_init();
           curl_setopt($ch, CURLOPT_URL, $url);
           curl_setopt($ch, CURLOPT_POST, true);
           curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
           curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: nigerianyellowpages.com", 'Referer: http://nigerianyellowpages.com/searchByName_g.php'));
           $result = curl_exec($ch);
           //return $result;
           curl_close($ch); */
        echo $url = "http://nigerianyellowpages.com/search-name_g.php?search={$skey}&locationcoded={$myCityID}&cat=&subcat=&spage=0&page=0";
        $return = file_get_contents($url);
        //echo "curl returned FSTR LEN " . ($return) . '<br>';
        $preg_match1 = '<table class="style84" cellspacing="1" cellpadding="5" border="0" width="97%">(.+)</table><br>';
        $preg_match2 = '<a href="(.+)"><b>(\\d{,1})</b></a>';
        $preg_all = '<td (.+) />(.+)</td>';
        /* $preg_phone = '<td align="left" valign="center" width="20%" bgcolor="#FFFF99" />(.+)</td>';
           $preg_addr = '<td align="left" valign="center" width="20%" bgcolor="#FFFF99" />(.+)</td>'; */
        $inner = 0;
        //echo 'line 223<br>';
        if (preg_match("~{$preg_match1}~Usi", $return, $matches)) {
            //echo '<br>**************************************************** first PM *****************************************<br>';
            //var_dump($matches[1]);
            //echo 'line 227<br>';
            if (preg_match_all('~<tr>(.+)</tr>~Usi', $matches[1], $mRow)) {
                //echo '<br>****************************************** second PM ***********************************************<br>';
                //var_dump($mRow[1]);
                //echo '<br>****************************************** second PM END***********************************************<br>';
                //echo 'line 232<br>';
                $arTmp[] = 'name';
                $arTmp[] = 'phone';
                $arTmp[] = 'addr';
                //echo '<br>Size1: '.count($mRow[1]);
                foreach ($mRow[1] as $key => $valueOuter) {
                    //echo 'line 238<br>';
                    if (preg_match_all("~{$preg_all}~Usi", $valueOuter, $mAll)) {
                        //echo '<br>Size2: '.count($mAll[1]);
                        foreach ($mAll[2] as $valueInner) {
                            //echo "<br>inner foreach $index - $inner<br>";
                            if ($inner != 0) {
                                $tmp = trim(strip_tags($valueInner));
                                if (substr($tmp, 0, 1) == ',') {
                                    echo '<br>' . ($tmp = substr($tmp, 1));
                                }
                                $arData[$index][$arTmp[$inner - 1]] = $tmp;
                            }
                            $inner++;
                            if ($inner > 3) {
                                $index++;
                                $inner = 0;
                            }
                        }
                        //$arData[$index]['name'] = strip_tags($mName[1]);
                    }
                    //$index++;
                }
            }
        }
    }
    if ($arData) {
        var_dump($arData);
        //$total_return = implode("\n\n", implode("\n",$arData));
        $total_return = '';
        foreach ($arData as $value) {
            $total_return .= implode(" - ", $value);
            $total_return .= "\n";
        }
        return true;
    } elseif ($myCityID) {
        $total_return = "Sorry no restaurant found for this city";
        return true;
    }
    return false;
}
    die("Could not connect to database server.  Sever Error Message: " . mysqli_error($connection));
}
if (isset($_GET['term'])) {
    $term = $_GET['term'];
} else {
    $term = " ";
}
$sql = "SELECT * FROM `Organizations`";
$result = mysqli_query($connection, $sql);
$Response = array();
$searchTermList = explode(" ", $term);
$searchTermsMetas = array();
foreach ($searchTermList as $t) {
    $m = metaphone($t);
    array_push($searchTermsMetas, $m);
}
while ($row = mysqli_fetch_assoc($result)) {
    $orgNameList = explode(" ", $row['Name']);
    foreach ($orgNameList as $o) {
        $orgMeta = metaphone($o);
        foreach ($searchTermsMetas as $s) {
            if ($orgMeta === $s) {
                if (!in_array($row, $Response)) {
                    array_push($Response, $row);
                }
            }
        }
    }
}
$res = json_encode($Response);
echo $res;
Example #28
0
 /**
  * Creating metaphone based hash from input word
  *
  * @param	string		Word to convert
  * @param	boolean		If set, returns the raw metaphone value (not hashed)
  * @return	mixed		Metaphone hash integer (or raw value, string)
  */
 function metaphone($word, $retRaw = FALSE)
 {
     if (is_object($this->metaphoneObj)) {
         $tmp = $this->metaphoneObj->metaphone($word, $this->conf['sys_language_uid']);
     } else {
         $tmp = metaphone($word);
     }
     // Return raw value?
     if ($retRaw) {
         return $tmp;
     }
     // Otherwise create hash and return integer
     if ($tmp == '') {
         $ret = 0;
     } else {
         $ret = hexdec(substr(md5($tmp), 0, 7));
     }
     return $ret;
 }
Example #29
-1
function check_tips_content($cachekey)
{
    global $tips, $key_matched;
    //echo "CHACHE CONTENT<br>";
    //var_dump($cachekey);
    //checking keys
    $words_splited = explode(" ", $tips);
    //var_dump($words_splited);
    $prev_word = "";
    foreach ($words_splited as $word) {
        $prev_word .= " {$word}";
        echo "<br>TIPS " . ($prev_word = trim($prev_word));
        foreach ($cachekey as $key => $value) {
            //echo "KEY : $key<br>";
            if (metaphone($prev_word) == metaphone($key)) {
                $key_matched = $key;
                $tips = str_replace($prev_word, '', $tips);
                break;
            } else {
                foreach ($value as $v) {
                    //echo "VALUE : $v<br>";
                    if (metaphone($prev_word) == metaphone($v)) {
                        $key_matched = $key;
                        $tips = str_replace($prev_word, '', $tips);
                        break;
                    }
                }
            }
        }
    }
}
Example #30
-1
     $query = "SELECT * from tvnow_channel where name like '" . $sub . "%'";
     $result = mysql_query($query);
     echo "<br>Like Query, Count" . mysql_num_rows($result);
     if (mysql_num_rows($result) == 0) {
         $query = "SELECT * from tvnow_channel";
         $result = mysql_query($query);
         echo "<br>Query, Count" . mysql_num_rows($result);
     }
 }
 $i = 0;
 $m2 = metaphone($tv_req);
 while ($row = mysql_fetch_array($result)) {
     $tvname[$i] = trim($row['name']);
     $tvdname[$i] = trim($row['dname']);
     $tvlink[$i] = trim($row['link']);
     $m1 = metaphone($tvname[$i]);
     //$lev_arry[$i] = levenshtein($m1, $m2);
     $sim[$i] = similar_text($m1, $m2, $perc);
     $percent[$i] = $perc;
     echo 'similarity: ' . $tvdname[$i] . ' : ' . $sim[$i] . ', ' . $perc . '% <br>';
     $i++;
     //            $isfound = true;
 }
 if ($tvmust) {
     $highest = 75;
 } else {
     $highest = 85;
 }
 $hkey = -1;
 foreach ($percent as $key => $pr) {
     if ($pr >= $highest) {