我有两个 preg_match() 调用,我想合并数组而不是替换第一个数组。 到目前为止我的代码:
$arr = Array();
$string1 = "Article: graphics card";
$string2 = "Price: 300 Euro";
$regex1 = "/Article[:] (?P<article>.*)/";
$regex2 = "/Price[:] (?P<price>[0-9]+) Euro/";
preg_match($regex1, $string1, $arr);
//output here:
$arr['article'] = "graphics card"
$arr['price'] = null
preg_match($regex2, $string2, $arr);
//output here:
$arr['article'] = null
$arr['price'] = "300"
我如何匹配,所以我的输出将是:
$arr['article'] = "graphics card"
$arr['price'] = "300"
?
preg_replace_callback
并处理回调函数内的合并。
如果是我,这就是我会这样做的方式,这将允许以后更容易扩展,并避免使用回调函数。它还可以通过用单个字符串 var 替换 $strs[$key]
和 $strs
数组来支持轻松搜索一个字符串。它不会删除数字键,但如果您只是继续从数组中访问关联键,这永远不会引起问题。
$strs = array();
$strs[] = "Article: graphics card";
$strs[] = "Price: 300 Euro";
$regs = array();
$regs[] = "/Article[:] (?P<article>.*)/";
$regs[] = "/Price[:] (?P<price>[0-9]+) Euro/";
$a = array();
foreach( $regs as $key => $reg ){
if ( preg_match($reg, $strs[$key], $b) ) {
$a += $b;
}
}
print_r($a);
/*
Array
(
[0] => Article: graphics card
[article] => graphics card
[1] => graphics card
[price] => 300
)
*/
结果存储在两个不同的数组中,则可以使用array_merge。但是上面描述的输出不正确。如果您在字符串中使用 regex1 进行搜索,则没有 $arr['price'],而只有 $arr['article']。第二preg_match也是如此。这意味着,如果您将一个结果存储在 $arr 中,一个存储在 $arr 2 中,则可以将它们合并到一个数组中。
preg_match不提供功能本身。
- 使用不同的数组进行第二次preg_match,比如
$arr2
- 遍历
$arr2
为$key => $value
。 - 从
$arr[$key]
和$arr2[$key]
中选择非空值,并将该值写入$arr[$key]
。 -
$arr
将需要合并的数组。
这应该适用于您的示例:
array_merge( // selfexplanatory
array_filter( preg_match($regex1, $string1, $arr)?$arr:array() ), //removes null values
array_filter( preg_match($regex2, $string2, $arr)?$arr:array() )
);