PHP explode String with Data Pairs - php

I have a dataset and I want to conevert it into an array and I just can't figure out how...
I've tried a couple things like preg_replace() with regex and explode() but it doesn't come out the way I need it.
So my dataset looks like this:
dataCrossID=12345, DeviceID=[ID=1234567]
dataCrossID=5678, DeviceID=[ID=7654321]
dataCrossID=67899, DeviceID=[ID=87654321]
and the Array should look like this:
$dataSet(
[12345] => 1234567,
[5678] => 7654321,
[67899] => 87654321,
)
I tried regex but the fact that the numbers got different lenghts makes it hard for me.
Does anyone have an idea?

The easiest way would be using preg_match_all with an simple regular expression.
$data = 'dataCrossID=12345, DeviceID=[ID=1234567]
dataCrossID=5678, DeviceID=[ID=7654321]
dataCrossID=67899, DeviceID=[ID=87654321]';
preg_match_all('/=([0-9]+).*=([0-9]+)/', $data, $matches, PREG_SET_ORDER);
$dataSet = [];
foreach ($matches as $match) {
$dataSet[$match[1]] = $match[2];
}
print_r($dataSet);

Use preg_match_all() to identify the pieces of text you need:
$input = <<< E
dataCrossID=12345, DeviceID=[ID=1234567]
dataCrossID=5678, DeviceID=[ID=7654321]
dataCrossID=67899, DeviceID=[ID=87654321]
E;
preg_match_all('/dataCrossID=(\d+), DeviceID=\[ID=(\d+)\]/', $input, $matches, PREG_SET_ORDER);
print_r($matches);
The content of $matches is:
Array
(
[0] => Array
(
[0] => dataCrossID=12345, DeviceID=[ID=1234567]
[1] => 12345
[2] => 1234567
)
[1] => Array
(
[0] => dataCrossID=5678, DeviceID=[ID=7654321]
[1] => 5678
[2] => 7654321
)
[2] => Array
(
[0] => dataCrossID=67899, DeviceID=[ID=87654321]
[1] => 67899
[2] => 87654321
)
)
You can now iterate over $matches and use the values at positions 1 and 2 as keys and values to extract the data into the desired array:
$output = array_reduce(
$matches,
function(array $c, array $m) {
$c[$m[1]] = $m[2];
return $c;
},
array()
);
print_r($output);
The output is:
Array
(
[12345] => 1234567
[5678] => 7654321
[67899] => 87654321
)

Related

PHP preg_split. Can't find or figure out ex for this

I did try but can't find or figure out regex for the following
Working in PHP need preg_split to work
{password=123456, telephone=9452979342}/{Accept=application/json, Authorization=Bearer kadaljdlkadjsdaskdjaskdasdf}
What I want is to split this string into array like this:
Split by '/' in middle
[0] => {password=123456, telephone=9452979342}
[2] => {Accept=application/json, Authorization=Bearer kadaljdlkadjsdaskdjaskdasdf}
Select between {*}
[0] => password=123456, telephone=9452979342
[2] => Accept=application/json, Authorization=Bearer kadaljdlkadjsdaskdjaskdasdf
As per your way , you may try the following approach as well
$re = '/\}\/\{/m';
$str = '{password=123456, telephone=9452979342}/{Accept=application/json, Authorization=Bearer kadaljdlkadjsdaskdjaskdasdf}';
$arr=preg_split($re,$str);
$cnt=0;
foreach($arr as $values)
$arr[$cnt++]=preg_replace('/[{}]/','',$values);
print_r($arr);
run here
Is that what you want:
$str = "{password=123456, telephone=9452979342}/{Accept=application/json, Authorization=Bearer kadaljdlkadjsdaskdjaskdasdf}";
preg_match('~\{(.+?)\}/\{(.+?)\}~', $str, $matches);
print_r($matches);
Output:
Array
(
[0] => {password=123456, telephone=9452979342}/{Accept=application/json, Authorization=Bearer kadaljdlkadjsdaskdjaskdasdf}
[1] => password=123456, telephone=9452979342
[2] => Accept=application/json, Authorization=Bearer kadaljdlkadjsdaskdjaskdasdf
)

Given a string create a multidimensional array with named keys usign a regex

I'm using PHP. Given, for example, the following string:
$str = "a2c4-8|a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]|a30"
and exploding it by | I get the strings:
a2c4-8
a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]
a30
Now I would like to separate the digits that follow the a from all the other characters, remove the letters a and c (keep dashes, commas and square brackets) and place the results in a multidimensional array as follows:
Array
(
[0] => Array
(
[a] => 2
[c] => 4-8
)
[1] => Array
(
[a] => 6
[c] => 2,3-5,6[2],8[4]-10,14-21[5]
)
[2] => Array
(
[a] => 30
[c] =>
)
)
a is always followed by digit and after this digit there may be or may not be a c followed by other comma separated strings.
Notice that in the resulting array the letters a and c have been removed. All other characters have been kept. I tried to modify this answer by Casimir et Hippolyte but without success.
A plus would be avoid to add to the resulting array empty array keys (as the last [c] above).
Consider the following solution using preg_match_all function with named submasks((?P<a>)...) and PREG_SET_ORDER flag, array_map, array_filter, array_column(available since PHP 5.5) and trim functions:
$str = "a2c4-8|a6c2,c3-5,c6[2],c8[4]-10,c14-21[5]|a30";
$parts = explode("|", $str);
$result = array_map(function ($v) {
preg_match_all("/(?P<a>a\d+)?(?P<c>c[0-9-\[\]]+)?/", $v, $matches, PREG_SET_ORDER);
$arr = [];
$a_numbers = array_filter(array_column($matches, "a"));
$c_numbers = array_filter(array_column($matches, "c"));
if (!empty($a_numbers)) {
$arr['a'] = array_map(function($v){ return trim($v, 'a'); }, $a_numbers)[0];
}
if (!empty($c_numbers)) {
$arr['c'] = implode(",", array_map(function($v){ return trim($v, 'c'); }, $c_numbers));
}
return $arr;
}, $parts);
print_r($result);
The output:
Array
(
[0] => Array
(
[a] => 2
[c] => 4-8
)
[1] => Array
(
[a] => 6
[c] => 2,3-5,6[2],8[4]-10,14-21[5]
)
[2] => Array
(
[a] => 30
)
)
P.S. "empty array keys" are also omitted

PHP: preg_match_all() - divide an array

I have the following code:
$str = '{"ok1", "ok2"},
{"ok3", "ok4"},
{"ok5", "ok6"}';
preg_match_all('/"([^"]*)"/', $str, $matches);
print_r($matches[1]);
which outputs this:
Array ( [0] => ok1 [1] => ok2 [2] => ok3 [3] => ok4 [4] => ok5 [5] => ok6 )
It works perfect but I want to make it array1, array2 and array3. So it will divide the array depending on the tags inside {}
i.e.
`array1` will be `array("ok1", "ok2")`;
`array2` will be `array("ok3", "ok4")`;
`array3` will be `array("ok5", "ok6")`;
Kind of an overkill, but you could indeed achieve it with two regular expressions as well (if this is not some JSON code):
<?php
$string = '{"ok1", "ok2"}, {"ok3", "ok4"}, {"ok5", "ok6"}';
$regex = '~(?<=}),\s~';
$result = array();
$parts = preg_split($regex, $string);
foreach ($parts as $part) {
preg_match_all('~"(?<values>[^"]+)"~', $part, $elements);
$result[] = $elements["values"];
}
echo $result[0][1]; // ok2
?>
Jan's answer is very good and I am only posting mine here as a different way to approach the problem using regex - not to take away from his answer.
If you had a string like this:
$output_array = array();
$str = '{"ok1", "ok2", "ok9", "ok11"},
{"ok3", "ok4"},
{"ok5", "ok6", "ok99"}';
Then you could look for all sets of curly braces and store those into an array:
preg_match_all('~\{.*?\}~', $str, $matches);
Finally, just loop through each set of braces and match each set of data appearing in quotation marks. Then add those matches to your output array.
foreach ($matches[0] AS $set) {
preg_match_all('~".*?"~', $set, $set_matches);
$output_array[] = $set_matches[0];
}
print_r($output_array);
That will give you an array like this:
Array
(
[0] => Array
(
[0] => "ok1"
[1] => "ok2"
[2] => "ok9"
[3] => "ok11"
)
[1] => Array
(
[0] => "ok3"
[1] => "ok4"
)
[2] => Array
(
[0] => "ok5"
[1] => "ok6"
[2] => "ok99"
)
)

PHP - What regex code do I need to match this boundary sequence?

I have the following text string:
-asc100-17-asc100-17A-asc100-17BPH-asc100-17ASL
What regex code do I need to extract the values so that they appear in the matches array like this:
-asc100-17
-asc100-17A
-asc100-17BPH
-asc100-17ASL
Thanks in advance!
You may try this:
$str = "-asc100-17-asc100-17A-asc100-17BPH-asc100-17ASL";
preg_match_all('/-asc\d+-[0-9a-zA-Z]+/', $str, $matches);
// Print Result
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => -asc100-17
[1] => -asc100-17A
[2] => -asc100-17BPH
[3] => -asc100-17ASL
)
)
Based on the very limited information in your question, this works:
-asc100-17[A-Z]*
Debuggex Demo
If you want to capture the post -asc100- code, then use
-asc100-(17[A-Z]*)
Which places 17[the letters] into capture group one.
Might use preg_split with a lookahead as well for your scenario:
print_r(preg_split('/(?=-asc)/', $str, -1, PREG_SPLIT_NO_EMPTY));
Are you trying to break the string in an array? Then why regex is required? This function can handle what you want:
$arr = explode('-asc', '-asc100-17-asc100-17A-asc100-17BPH-asc100-17ASL');
foreach ($arr as $value) {
if(!empty($value)){
$final[] = '-asc'.$value;
}
}
print_r($final);
Output array : Array ( [0] => -asc100-17 [1] => -asc100-17A [2] => -asc100-17BPH [3] => -asc100-17ASL )

get an array with a predefined structure using preg_match or preg_match_all

Here is an example string:
"60 reviews from 12 people, 20% of users"
(Let's call it $v)
I have been using preg_match_all to get an array with all the numbers
$pattern = '!\d+!';
preg_match_all($pattern, $v, $matches, PREG_SET_ORDER);
The result I get is:
Array
(
[0] => Array
(
[0] => 60
)
[1] => Array
(
[0] => 12
)
[2] => Array
(
[0] => 20
)
)
But despite trying for some time I haven't been able to get what I want. What I want is this:
Array
(
[0] => 60
[1] => 12
[2] => 20
)
Maybe should I be using preg_match instead? but with preg_match I only get one value... Or maybe along with a loop? It looks like an ugly hack... There should be a profesional way out there... Thanks in advance to PHP experts! ;)
Presuming the format always stays the same, you can do the following:
<?php
// Input string/line
$v = "60 reviews from 12 people, 20% of users";
// Match regex (0-9; min 1 or max unlimited numbers)
preg_match_all("/[0-9]{1,}/", $v, $matches);
// Remove/sub key
$matches = $matches[0];
// Echo out
print_r($matches);
?>
This will output:
Array (
[0] => 60 // < Access using $matches[0]
[1] => 12 // < Access using $matches[1]
[2] => 20 // < Access using $matches[2]
)
Is this what you want?, array_values($array)

Categories