我在 PHP 中使用以下函数来检测包含“near”的字符串中的实体和位置preg_match();。有没有更优化的方法来为此编写代码?我使用了很多 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。
- 1 回答
- 0 关注
- 82 浏览
添加回答
举报
0/150
提交
取消