如何解决在PHP中优化preg_match
我正在PHP中使用以下函数,使用preg_match();
从其中包含“ near”的字符串中检测实体和位置。有没有更好的方法来为此编写代码?我正在使用很多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);
}
解决方法
使用preg_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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。