【问题标题】:php search on string comma separated and get element that matchphp搜索字符串逗号分隔并获取匹配的元素
【发布时间】:2016-07-09 12:56:54
【问题描述】:

我有一个问题,如果有人可以帮助我解决这个问题。我有一个用逗号分隔的字符串,我想找到一个部分匹配的项目:

$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";

作为过滤器的结果,我只需要从部分匹配中获取完整的字符串:

$result = "GenomaPrintOrder";

【问题讨论】:

  • 你用preg_match尝试过什么吗?
  • 如果您知道聚合字符串是如何粘合在一起的,您可以使用该粘合将字符串分解成一个数组并循环遍历它。
  • $matches = array_filter(explode(',', $string), function ($value) use ($search) { return strpos($value, $search) !== false; });
  • 即使您不接受好的答案,您也可以考虑点赞,我接受了。

标签: php regex filtering


【解决方案1】:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$result = array();
$tmp = explode(",", $string);
foreach($tmp as $entrie){
    if(strpos($entrie, $string) !== false)
        $result[] = trim($entrie);
}

这将为您提供一个包含与您的搜索字符串匹配的所有字符串的数组。

【讨论】:

    【解决方案2】:

    您可以使用正则表达式来获取结果:

    $search = "PrintOrder";
    $string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
    
    $regex = '/([^,]*' . preg_quote($search, '/') . '[^,]*)/';
    
    preg_match($regex, $string, $match);
    
    $result = trim($match[1]); // $result == 'GenomaPrintOrder'
    

    【讨论】:

      【解决方案3】:
      $search = "PrintOrder";
      $string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
      
      
      $array = explode(" ", $string);
      echo array_filter($array, function($var) use ($search) { return preg_match("/\b$searchword\b/i", $var); });
      

      【讨论】:

        【解决方案4】:

        使用preg_match_all,您可以这样做。

        PHP 代码

        <?php
          $subject = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView, NewPrintOrder";
          $pattern = '/\b([^,]*PrintOrder[^,]*)\b/';
          preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
          foreach ($matches as $val) {
              echo "Matched: " . $val[1]. "\n";
          }
        ?>
        

        输出

        Matched: GenomaPrintOrder
        Matched: NewPrintOrder
        

        Ideone Demo

        【讨论】:

        • 得到这个错误:警告:preg_match():编译失败:在偏移量 25 处没有可重复的内容
        • @WalterNuñez:我已经编辑了代码。请检查。在最新示例中,我添加了一个额外的字符串 NewPrintOrder 来演示多个匹配项。
        【解决方案5】:

        既然已经有这么多不同的答案,这里是另一个:

        $result = preg_grep("/$search/", explode(", ", $string));
        print_r($result);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多