我有一个问题,如果有人可以帮我解决这个问题。我有一个用逗号分隔的字符串,我想找到一个部分匹配的项目:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
由于过滤器,我只需要从部分匹配中获取完整的字符串:
$result = "GenomaPrintOrder";
答案 0 :(得分:2)
使用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 强>
答案 1 :(得分: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 :(得分:1)
您可以使用正则表达式来获得结果:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$regex = '/([^,]*' . preg_quote($search, '/') . '[^,]*)/';
preg_match($regex, $string, $match);
$result = trim($match[1]); // $result == 'GenomaPrintOrder'
答案 3 :(得分:1)
$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 :(得分:0)
由于已经有很多不同的答案,这是另一个答案:
$result = preg_grep("/$search/", explode(", ", $string));
print_r($result);