LostPhysx
LostPhysx

Reputation: 3641

How to append output of preg_match to an existing array?

I have two preg_match() calls and i want to merge the arrays instead of replacing the first array. my code so far:

$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"

How may I match so my output will be:

$arr['article'] = "graphics card"
$arr['price'] = "300"

?

Upvotes: 1

Views: 1502

Answers (5)

Pebbl
Pebbl

Reputation: 36065

If it were me this is how I would do it, this would allow for easier extension at a later date, and would avoid using a callback function. It could also support searching one string easily by replacing $strs[$key] and the $strs array with a singular string var. It doesn't remove the numerical keys, but if you are only ever to go on accessing the associative keys from the array this will never cause a problem.

$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
)
*/

Upvotes: 1

Brendan Smith
Brendan Smith

Reputation: 346

You could use preg_replace_callback and handle the merging inside the callback function.

Upvotes: 1

DhruvPathak
DhruvPathak

Reputation: 43255

  1. Use different array for second preg_match ,say $arr2
  2. Traverse $arr2 as $key => $value .
  3. Choose non null value out of $arr[$key] and $arr2[$key], and write that value to $arr[$key].
  4. $arr will have required merged array.

Upvotes: 0

Udan
Udan

Reputation: 5609

This should work for your example:

array_merge( // selfexplanatory
           array_filter( preg_match($regex1, $string1, $arr)?$arr:array() ), //removes null values
           array_filter( preg_match($regex2, $string2, $arr)?$arr:array() ) 
  );

Upvotes: -1

eX0du5
eX0du5

Reputation: 896

You can use array_merge for this if you store your results in two different arrays. But your output depicted above is not correct. You do not have $arr['price'] if you search with regex1 in your string but only $arr['article']. Same applies for the second preg_match. That means if you store one result in $arr and one in $arr2 you can merge them into one array.

preg_match does not offer the functionality itself.

Upvotes: 0

Related Questions