尝试在PHP搜索中将完整状态名称替换为缩写

时间:2011-09-17 04:18:42

标签: php mysql html

我正试图在城市/州/邮编搜索中用IL取代伊利诺伊州;或者,任何国家。我将状态存储为abbr。所以我需要那个在输入搜索中。我在尝试:

if(isset($_GET['search_loc'])&&isset($_GET['search_style'])) {
    $search_loc = $_GET['search_loc'];
    $search_style = $_GET['search_style'];
    if(!empty($search_loc)||!empty($search_style)) {

        /* HERE!!! */ $search_loc = str_replace('Illinois', 'IL', $search_loc); // ***Here!!!***

        $query = "SELECT
                    name, street, city, state, zip_code, phone_number, style, description, time
                  FROM music_spots
                  WHERE CONCAT(city, ', ', state, ', ', zip_code) LIKE '%$search_loc%' // and so on...

但是,这不起作用。有关如何做到这一点的任何想法?谢谢。

3 个答案:

答案 0 :(得分:1)

我强烈建议使用数据库存储和检索州名。我可以向你保证硬编码不是答案。

答案 1 :(得分:1)

你应该真正使用地理定位/地址服务。以这种方式搜索SQL数据库根本不会使用索引,并且随着数据集的增长将变得非常慢。

如果地理定位不是一个可行的选项,您至少可以使用fulltext index并在fulltext列中使用另一个包含city,state,state_abbr和zip的表。因此,在此示例中,您将索引“Chicago IL Illinois 60605”。这也可以找到像“芝加哥IL伊利诺斯州60610”这样的匹配较少的结果,但这绝不是地理定位搜索。

然后,您只需使用用户的输入搜索location表,并将其加入另一个表:

SELECT 
m.name, m.street, m.city, m.state, m.zip_code, m.phone_number, m.style, m.description, m.time, 
MATCH (loc.location) AGAINST ('Chicago, IL 60605') as score
FROM location AS loc
INNER JOIN music_spots AS m ON m.location_id = loc.id
WHERE MATCH (loc.location) AGAINST ('Chicago, IL 60605');

或全名:

SELECT 
m.name, m.street, m.city, m.state, m.zip_code, m.phone_number, m.style, m.description, m.time,
MATCH (loc.location) AGAINST ('Chicago, Illinois 60605') as score
FROM location AS loc
INNER JOIN music_spots AS m ON m.location_id = loc.id
WHERE MATCH (loc.location) AGAINST ('Chicago, Illinois 60605');

答案 2 :(得分:0)

你可以做一个非常简单的功能:

function abbreviate_state($state_to_abreviate){
    //This information never changes
    $full_state = array('Alabama', 'Alazka', 'Arizona'); //for the 50 states
    $ab_state   = array('AL','AK', 'AZ');
    //Here we search and replace the state with the abbreviation
    return str_replace($full_state, $ab_state, $state_to_abreaviate);
}

您可以将其放在 function.php中,无论身在何处,都可以随时拨打电话。