php 搜索以逗号分隔的字符串并获取匹配的元素

php search on string comma separated and get element that match

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

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

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

$result = "GenomaPrintOrder";
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$result = array();
$tmp = explode(",", $string);
foreach($tmp as $entrie){
    if(strpos($entrie, $string) !== false)
        $result[] = trim($entrie);
}

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

您可以使用正则表达式得到结果:

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

$regex = '/([^,]*' . preg_quote($search, '/') . '[^,]*)/';

preg_match($regex, $string, $match);

$result = trim($match[1]); // $result == 'GenomaPrintOrder'
$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); });

使用 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

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

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