【问题标题】:Optimizing preg_match() in PHP在 PHP 中优化 preg_match()
【发布时间】:2020-12-07 00:48:15
【问题描述】:

我在 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);

}

【问题讨论】:

  • 所以您想查看字符串是否包含特定的“短语/单词”?

标签: php arrays if-statement optimization preg-match


【解决方案1】:

使用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,可选地后跟bymy locationme

【讨论】:

  • 嗯,我在实现它时遇到了麻烦。你的意思是把 $entityAndLocation = array("entity" => null, "location" => null);在$击穿之前?另外,$1 是否意味着 $q?
  • 是的,这只是替换了所有if 语句,没有别的。
  • 我将你的函数与“西雅图附近的红知更鸟”一起使用,我得到一个空数组作为输出。具体来说,数组 ( [entity] => [location] => )
  • 抱歉,错字,:? 应该是 ?:
  • 奇怪,我改了:? to ?: 但我仍然得到一个空的 $entityAndLocation 数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多