第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

優(yōu)化 PHP 中的 preg_match()

優(yōu)化 PHP 中的 preg_match()

PHP
慕工程0101907 2023-10-15 16:39:29
我在 PHP 中使用以下函數來檢測包含“near”的字符串中的實體和位置preg_match();。有沒有更優(yōu)化的方法來為此編寫代碼?我使用了很多 if 語句,似乎可以改進,但我不確定如何改進。// Test cases$q = "red robin near seattle";//$q = "red robin near me";//$q = "red robin nearby";//$q = "red robin near my location";function getEntityAndLocation($q){    $entityAndLocation = array("entity" => null, "location" => null);    if(preg_match('(nearby)', $q) === 1) {        $breakdown = explode("nearby", $q);        $entityAndLocation["entity"] = $breakdown[0];        $entityAndLocation["location"] = $breakdown[1];        return $entityAndLocation;    }    if(preg_match('(near my location)', $q) === 1) {        $breakdown = explode("near my location", $q);        $entityAndLocation["entity"] = $breakdown[0];        $entityAndLocation["location"] = $breakdown[1];        return $entityAndLocation;    }    if(preg_match('(near me)', $q) === 1) {        $breakdown = explode("near me", $q);        $entityAndLocation["entity"] = $breakdown[0];        $entityAndLocation["location"] = $breakdown[1];        return $entityAndLocation;    }    if(preg_match('(near)', $q) === 1) {        $breakdown = explode("near", $q);        $entityAndLocation["entity"] = $breakdown[0];        $entityAndLocation["location"] = $breakdown[1];        return $entityAndLocation;    }}if(preg_match('(near)', $q) === 1) {  $entityAndLocation = getEntityAndLocation($q);  print_r($entityAndLocation);}
查看完整描述

1 回答

?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

usepreg_split()使用正則表達式作為分隔符來分割字符串。您可以編寫一個匹配所有模式的正則表達式。


function getEntityAndLocation($q){


    $entityAndLocation = array("entity" => null, "location" => null);


    $breakdown = preg_split('/near(?:by| my location| me)?/', $q);

    if (count($breakdown) >= 2) {

        $entityAndLocation["entity"] = $breakdown[0];

        $entityAndLocation["location"] = $breakdown[1];

        return $entityAndLocation;

    }

    return $entityAndLocation;

}

正則表達式匹配near,可以選擇后跟by, my location, 或me。


查看完整回答
反對 回復 2023-10-15
  • 1 回答
  • 0 關注
  • 128 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號