我在 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);}
優(yōu)化 PHP 中的 preg_match()
慕工程0101907
2023-10-15 16:39:29