php - 在 PHP 中优化 preg_match()
问题描述
我在 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);
}
解决方案
用于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
.
推荐阅读
- scala - org.apache.spark.sql.AnalysisException:无法解析给定输入列的“AB”:无法解析 spark sql 查询中的变量
- mysql - 当连接子句包含条件时,外部连接行为异常
- html - HTML 按钮样式不正确
- haskell - 计算列表中每个元素的所有出现次数
- android - 无法从命令行执行 sdk manager 命令:Android
- sql - 在 sql 中使用 group by over id 对重叠值或日期进行求和/计数
- google-chrome - Overscroll Navigation Flag not working on Chome command line
- typescript - 如何键入一个函数,该函数包装了一个承诺返回函数,并返回一个原始函数的类型?
- elasticsearch - Elasticsearch 倒排索引
- python - Wait till NSTask completes its execution of terminal command