我有一个问题,是否有人可以帮我解决这个问题。我有一个用逗号分隔的字符串,我想找到一个部分匹配的项目:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
我只需要从部分匹配中获取完整的字符串作为过滤器的结果:
$result = "GenomaPrintOrder";
有了
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
$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); });
既然已经有很多不同的答案,这里是另一个:
$result = preg_grep("/$search/", explode(", ", $string));
print_r($result);