【问题标题】:In PHP what's the best way of filtering out sets of words from plain text在PHP中,从纯文本中过滤掉单词集的最佳方法是什么
【发布时间】:2015-12-09 11:16:14
【问题描述】:

假设您有纯文本输入。在该文本中,您有要查找的关键词。说“成本”、“位置”和“材料”,您想过滤掉这些关键词之后的词,以便稍后将它们存储在数据库中包含这些关键词的列下。

你会怎么做?我正在考虑将字符串转换为数组,然后搜索它并使用键值来计算关键字之间的单词范围。这只是一个想法,有人有更好的想法吗?

示例输入:

Cost £45 Materials glue, plastic, wood and nails Location Sale, Manchester North England.

在 vars 中这样分组的内容:

$cost = "£45";
$materials = "glue, plastic, wood and nails";
$location = "Sale, Manchester North England";

【问题讨论】:

    标签: php regex search substring preg-match


    【解决方案1】:

    您可以使用此正则表达式来匹配您的值:

    \s*\bCost\s+(?<cost>.+?)\s*\bMaterials\s+(?<material>.+?)\s*\bLocation\s+(?<location>.+)
    

    RegEx Demo

    代码:

    $re = '/\s*\bCost\s+(?<cost>.+?)\s*\bMaterials\s+(?<material>.+?)\s*\bLocation\s+(?<location>.+)/'; 
    
    preg_match($re, $str, $matches);
    
    print_r($matches);
    

    您将在$matches 数组中获得匹配的值,索引名称指示它匹配的值。

    【讨论】:

      【解决方案2】:

      要获取模式匹配之间的文本,您可以使用preg_split。在这种情况下,我建议使用word boundaries (\b) 匹配您的任何关键字,这样您就可以解析带有不特定顺序的关键字的文本。

      正则表达式:

      /\b(Cost|Materials|Location)\b/i
      

      为了在preg_split 的结果中包含关键字,我们使用PREG_SPLIT_DELIM_CAPTURE flag

      preg_split($re, $str, -1, PREG_SPLIT_DELIM_CAPTURE);
      

      还返回第一个关键字匹配之前的文本。我们将使用array_shift() 将其丢弃。

      代码:

      $re = '/\b(Cost|Materials|Location)\b/i'; 
      $str = "<preceding text> Cost £45 Materials glue, plastic, wood and nails Location Sale, Manchester North England."; 
      
      //$re matches keywords, but also captures them... PREG_SPLIT_DELIM_CAPTURE includes the captures in the result
      $result = preg_split($re, $str, -1, PREG_SPLIT_DELIM_CAPTURE);
      
      //Remove preceding text
      array_shift($result);
      print_r($result);
      

      结果

      Array
      (
          [0] => Cost
          [1] =>  £45 
          [2] => Materials
          [3] =>  glue, plastic, wood and nails 
          [4] => Location
          [5] =>  Sale, Manchester North England.
      )
      

      Run this code

      【讨论】:

        猜你喜欢
        • 2020-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-07
        相关资源
        最近更新 更多