How to append output of preg_match to an existing array? - php

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

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

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

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.

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

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() )
);

Related

Transform every two array items into associative array pairs

I'm trying to make an associative array from my string, but nothing works and I don't know where the problem is.
My string looks like:
$string = "somethink;452;otherthink;4554;somethinkelse;4514"
I would like to make an associative array, where "text" is the key, and the number is value.
Somethink => 452 otherthink => 4554 Somethinkelse => 4514
I tried to convert the string into an array and then to the associative array but it's not working. I decided to use:
$array=explode(";",$string);
Then tried to use a foreach loop but it's not working. Can somebody help?
Using regex and array_combine:
$string = "somethink;452;otherthink;4554;somethinkelse;4514";
preg_match_all("'([A-Za-z]+);(\d+)'", $string, $matches);
$assoc = array_combine($matches[1], $matches[2]);
print_r($assoc);
Using a traditional for loop:
$string = "somethink;452;otherthink;4554;somethinkelse;4514";
$arr = explode(";", $string);
for ($i = 0; $i < count($arr); $i += 2) {
$assoc[$arr[$i]] = $arr[$i+1];
}
print_r($assoc);
Result:
Array
(
[somethink] => 452
[otherthink] => 4554
[somethinkelse] => 4514
)
Note that there must be an even number of pairs; you can add a condition to test this and use a substitute value for any missing keys, or omit them.

php array of arrays to 1D array not getting properly as expected

I am reading value from CMD which is running a python program and my output as follows:
Let as assume those values as $A:
$A = [[1][2][3][4]....]
I want to make an array from that as:
$A = [1,2,3,4....]
I had tried as follows:
$val = str_replace("[","",$A);
$val = str_replace("]","",$val);
print_r($val);
I am getting output as:
Array ( [0] => 1 2 3 4 ... )
Please guide me
try this
// your code goes here
$array = array(
array("1"),
array("2"),
array("3"),
array("4")
);
$outputArray = array();
foreach($array as $key => $value)
{
$outputArray[] = $value[0];
}
print_r($outputArray);
Also check the example here https://ideone.com/qaxhGZ
This will work
array_reduce($a, 'array_merge', array());
Multidimensional array to single dimensional array,
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));
$A = iterator_to_array($it, false);
But, if $A is string
$A = '[[1][2][3][4]]';
$A = explode('][', $A);
$A = array_map(function($val){
return trim($val,'[]');
}, $A);
Both codes will get,
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
This function will work when you do indeed have a multidimensional array, which you stated you have, in stead of the String representation of a multidimensional array, which you seem to have.
function TwoDToOneDArray($TwoDArray) {
$result = array();
foreach ($TwoDArray as $value) {
array_push($result, $value[0]);
}
return $result;
}
var_dump(TwoDToOneDArray([[0],[1]]));
You can transform $A = [[1],[2],[3],[4]] into $B = [1,2,3,4....] using this following one line solution:
$B = array_map('array_shift', $A);
PD: You could not handle an array of arrays ( a matrix ) the way you did. That way is only for managing strings. And your notation was wrong. An array of arrays (a matrix) is declared with commas.
If you have a string like you wrote in the first place you can try with regex:
$a = '[[1][2][3][4]]';
preg_match_all('/\[([0-9\.]*)\]/', $a, $matches);
$a = $matches[1];
var_dump($a);
If $A is a string that looks like an array, here's one way to get it:
$A = '[[1][2][3][4]]';
print "[".str_replace(array("[","]"),array("",","),substr($A,2,strlen($A)-4))."]";
It removes [ and replaces ] with ,. I just removed the end and start brackets before the replacement and added both of them after it finishes. This outputs: [1,2,3,4] as you can see in this link.

Creating a dynamic PHP array

I am new PHP question and I am trying to create an array from the following string of data I have. I haven't been able to get anything to work yet. Does anyone have any suggestions?
my string:
Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35
I want to dynamically create an array called "My_Data" and have id display something like my following, keeping in mind that my array could return more or less data at different times.
My_Data
(
[Acct_Status] => active
[signup_date] => 2010-12-27
[acct_type] => GOLD
[profile_range] => 31-35
)
First time working with PHP, would anyone have any suggestions on what I need to do or have a simple solution? I have tried using an explode, doing a for each loop, but either I am way off on the way that I need to do it or I am missing something. I am getting something more along the lines of the below result.
Array ( [0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35} )
You would need to explode() the string on , and then in a foreach loop, explode() again on the = and assign each to the output array.
$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35";
// Array to hold the final product
$output = array();
// Split the key/value pairs on the commas
$outer = explode(",", $string);
// Loop over them
foreach ($outer as $inner) {
// And split each of the key/value on the =
// I'm partial to doing multi-assignment with list() in situations like this
// but you could also assign this to an array and access as $arr[0], $arr[1]
// for the key/value respectively.
list($key, $value) = explode("=", $inner);
// Then assign it to the $output by $key
$output[$key] = $value;
}
var_dump($output);
array(4) {
["Acct_Status"]=>
string(6) "active"
["signup_date"]=>
string(10) "2010-12-27"
["acct_type"]=>
string(4) "GOLD"
["profile_range"]=>
string(5) "31-35"
}
The lazy option would be using parse_str after converting , into & using strtr:
$str = strtr($str, ",", "&");
parse_str($str, $array);
I would totally use a regex here however, to assert the structure a bit more:
preg_match_all("/(\w+)=([\w-]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);
Which would skip any attributes that aren't made up of letters, numbers or hypens. (The question being if that's a viable constraint for your input of course.)
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35';
parse_str(str_replace(',', '&', $myString), $myArray);
var_dump($myArray);

php - finding keys in an array that match a pattern

I have an array that looks like:
Array ( [2.5] => ABDE [4.8] => Some other value )
How would I find any key/value pair where the key matches a pattern? I will know the value of the first digit in the key,but not the second. so for example, using a prefix of "2.", I want to somehow be able to find the key "2.5" and return both the key and the value "ABDE".
I was thinking about using a regular expression with a pattern like:
$prefix = 2;
$pattern = '/'.$prefix.'\.\d/i';
and then looping through the array and checking each key. (by the way, just for demo purposes, $prefix has been hardcoded to 2, but in the real system, this is a value provided by the user's input).
I'm wondering if there's a simpler way to do this?
Thanks.
I think you need something like this:
$keys = array_keys($array);
$result = preg_grep($pattern, $keys);
The result will be a array that holds all the keys that match the regex. The keys can be used to retrieve the corresponding value.
Have a look at the preg_grep function.
you can simply loop through the array and check the keys
$array = array(...your values...);
foreach($array as $key => $value) {
if (preg_match($pattern,$key)){
// it matches
}
}
You can wrap it in a function and pass your pattern as parameter
Old question, but here's what I like to do:
$array = [ '2.5' => 'ABDE', '4.8' => 'Some other value' ];
preg_grep + array_keys will find all keys
$keys = preg_grep( '/^2\.\d/i', array_keys( $array ) );
You can add array_intersect_key and array_flip to extract a slice of the array that matches the pattern
$vals = array_intersect_key( $array, array_flip( preg_grep( '/^2\.\d/i', array_keys( $array ) ) ) );
For future programmers who encounter the same issue. Here is a more complete solution which doesn't use any loops.
$array = ['2.5'=> 'ABCDE', '2.9'=>'QWERTY'];
$keys = array_keys($array);
$matchingKeys = preg_grep('/^2\.+/', $keys);
$filteredArray = array_intersect_key($array, array_flip($matchingKeys));
print_r($filteredArray);
That are my ways
$data = ["path"=>"folder","filename"=>"folder/file.txt","required"=>false];
// FIRST WAY
$keys = array_keys($data);
if (!in_array("path", $keys) && !in_array("filename",$keys) && !in_array("required",$keys)) {
return myReturn(false, "Dados pendentes");
}
// SECOND WAY
$keys = implode("," array_keys($data));
if (!preg_match('/(path)|(filename)|(required)/'), $keys) {
return myReturn(false, "Dados pendentes");
}
To get just the part of the array with matching keys you could also write
$matching_array = array_flip(preg_grep($pattern, array_flip($your_array)));
This might just lead to problems performance-wise, if your array gets too big.
There's T-Regx library for regular expression in PHP, and it kas preg::grep_keys() method.
<?php
$array = [2.5 => 'ABDE', 4.8 => 'Some other value'];
preg::grep_keys("/$prefix\.\d/i", $array);

Given an array of arrays, how can I strip out the substring "GB" from each value?

Each item in my array is an array of about 5 values.. Some of them are numerical ending in "GB".. I need the same array but with "GB" stripped out so that just the number remains.
So I need to iterate through my whole array, on each subarray take each value and strip the string "GB" from it and create a new array from the output.
Can anyone recommend and efficient method of doing this?
You can use array_walk_recursive() for this:
array_walk_recursive($arr, 'strip_text', 'GB');
function strip_text(&$value, $key, $string) {
$value = str_replace($string, '', $value);
}
It's a lot less awkward than traversing an array with its values by reference (correctly).
You can create your own custom function to iterate through an array's value's, check if the substring GB exists, and if so, remove it. With that function you can pass the original array and the function into array_map
// i only did the subarray part
$diskSizes = array("500", "300 GB", "200", "120 GB", "130GB");
$newArray = array();
foreach ($diskSizes as $diskSize) {
$newArray[] = str_replace('GB', '', $diskSize);
}
// look at the new array
print_r($newArray);
$arr = ...
foreach( $arr as $k => $inner ) {
foreach( $inner as $kk => &$vv ) {
$vv = str_replace( 'GB', '', $vv );
}
}
This actually keeps the original arrays intact with the new strings. (notice &$vv, which means that i'm getting the variable by reference, which means that any changes to $vv within the loop will affect the actual string, not by copying)

Categories