【问题标题】:How to check array of strings to match with reference string in php?如何检查字符串数组以匹配php中的引用字符串?
【发布时间】:2026-02-13 11:10:01
【问题描述】:

我在 mysql 表中有数百万个字符串数据,并且必须与表中的字符串一一交叉检查,如果匹配返回 true 或 false。 我尝试了如下简单的 preg_match,这会消耗更多的内存和时间。

<?php

        $message = 'Hi xyz your account 123 credited Rs. 456 available balance is 789'; 
        $template = "/Hi .+? your account .+? credited Rs. .+? available balance is .+?/";
        $sql = "SELECT * FROM templates";

       $result = $conn->query($sql);

       $flag = false;

       if ($result->num_rows > 0) {
      // output data of each row
             while ($row = $result->fetch_assoc()) {
                     $template = $row["template"];
                      if (preg_match($template, $message)) {
                                $flag = true;
                                 break;
                       }
                       $flag = false;
               }
              $flag = false;
        }

        return $flag;

我也试过php_aho_corasick 但没用。请提出一些解决问题的好方法。 提前致谢。

编辑:我们有数百万个模板,这里是示例模板

$template1 = "/Hi .+? your account .+? credited Rs. .+? available balance is .+?/";
$template2 = "/Hi .+? your account .+? credited Rs. .+? available balance is .+? get more upate on/";
$templateN = "/Hello .+? click the link .+? to get your available balance./";

$message = "Hi xyz your account 123 credited Rs. 456 available balance is 789";

$message xyz, 123, 456, and 789 中的动态值会发生变化,现在必须与 N 个与消息匹配的模板进行交叉检查。如果我们将 template1 中的 .+? 替换为 message 那么将得到完全匹配,而 template2 有额外的单词,而 templateN 则完全不同。那么哪种方式是处理此类情况的更好方法。

【问题讨论】:

  • 也许一个好的解决方案是在你的 sql 中尝试正则表达式?

标签: php arrays string preg-match string-matching


【解决方案1】:

我认为您需要运行此查询;

SELECT * FROM `templates` WHERE message LIKE 'Hi % your account % credited Rs. % available balance is %'

所有结果都将匹配您的搜索,无需使用“preg_match”命令

【讨论】:

  • 谢谢,但我们不知道消息中哪个是动态值,可以直接用like子句查询。
  • @SudhirKoimattur 可能听不懂,但这个Hi % your account % credited Rs. % available balance is % 没有静态值。
【解决方案2】:

试试这个,让我们知道结果;它似乎在我的服务器上运行良好,而不会占用我的资源。在你的大桌子上试一试

$message = 'Hi xyz your account 123 credited Rs. 456 available balance is 789';

$sql5  = "SELECT template FROM templates ";
$sql5 .= "WHERE '$message' LIKE REPLACE( REPLACE(template,  '.+?', '%'),'/', '') ";
$qry5 = $connect->query($sql5) or trigger_error($connect->error, E_USER_ERROR);
$cnt5 = $qry5->num_rows;
    /* 
    echo $cnt5."<br>";
    //SHOWING RESULTS OF TEMPLATES THAT MATCH the message
    while($inf5 = $qry5->fetch_assoc()){
        $template = $inf5['template'];
        
        echo $template."<br>";
    }
    */

$flag = false;
if($cnt5>0){
    $flag = true;
}

【讨论】:

  • 你为什么不修改你之前的答案?
  • 嗨@Dominic,我尝试使用此代码对数百条记录正常工作,但再次因为我们有数百万条记录需要查询时间。我们有数百万条消息需要与数百万个模板进行交叉检查,是否有任何其他方式,例如弹性搜索,或者我们可以将模板存储在数组或内存或索引路径中,并对每条消息进行交叉检查,而无需进行任何查询来处理每次?
  • 每次运行脚本时,我都会使用另一个表或会话(临时)来保存最后检查的消息 ID。然后我调用该值并使用它来跳过所有已经检查过的消息。这仅在您不需要每次运行脚本时都检查所有消息时才有用
最近更新 更多