PHP: preg_match_all() - divide an array - php

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

Related

Get portion of PHP variable

I need to get only a part of a PHP variable.
$somevar = "sd300.somedata.cd.vm.someotherdata.cd.vm";
Now, I cannot figure out, but I only need this first part and do away with the last part, then save the variable again as $somevar
I only need to capture sd300.somdata.cd.vm
I've tried preg_replace but just cannot figure it out.
Does anyone have an idea?
If you still wanted to use preg_replace:
$somevar = "sd300.somedata.cd.vm.someotherdata.cd.vm";
$somevar = preg_replace("/(.*\..*\..*\..*)\..*\..*\..*/", '$1', $somevar);
var_dump($somevar);
Using preg_match_all() you can do this:
$somevar = "sd300.somedata.cd.vm.someotherdata.cd.vm";
$pattern = '/((.*?\.)(cd\.vm))/';
preg_match_all($pattern, $somevar, $matches);
print_r($matches);
Returns
Array
(
[0] => Array
(
[0] => sd300.somedata.cd.vm
[1] => .someotherdata.cd.vm
)
[1] => Array
(
[0] => sd300.somedata.cd.vm
[1] => .someotherdata.cd.vm
)
[2] => Array
(
[0] => sd300.somedata.
[1] => .someotherdata.
)
[3] => Array
(
[0] => cd.vm
[1] => cd.vm
)
)
$matches[0][0] contains the output you requested in your question.
The below logic would be helpful
$somevar = "sd300.somedata.cd.vm.someotherdata.cd.vm";
echo (implode('.',current(array_chunk(explode('.',$somevar),4))));
You can try to do this:
$somevar = "sd300.somedata.cd.vm.someotherdata.cd.vm";
$delimiter = '.cd.vm';
$temp = explode($delimiter, $somevar);
Your searched value:
$value = $temp[0] . $delimiter;
You didn't give a lot of information that is why I am guessing.

PHP explode String with Data Pairs

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
)

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
)

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 )

How to get the strings out of this?

I am trying to get some specific values out of the following string:
{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"
I want to get 'Toyota' out of that. The string is randomly generated, so it could be Benz or Pontiac.
Not really sure what this crazy string is from, but if you've accurately shown the format, this will extract the strings you're after:
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = array_filter(
explode(',',
preg_replace(
array('/"/', '/{/', '/:/', '"car"'),
array('', ',', '', ''),
$string
)
)
);
print_r($string);
// Output: Array ( [1] => Toyota [2] => honda [3] => BMW [4] => Hyundai )
... if, instead, this is just a horrible typeo and this is supposed to be JSON, use json_decode:
$string = '[{"car":"Toyota"},{"car":"honda"},{"car":"BMW"},{"car":"Hyundai"}]'; // <-- valid JSON
$data = json_decode($string, true);
print_r($data);
// Output: Array ( [0] => Array ( [car] => Toyota ) [1] => Array ( [car] => honda ) [2] => Array ( [car] => BMW ) [3] => Array ( [car] => Hyundai ) )
Documentation
preg_replace - http://php.net/manual/en/function.preg-replace.php
array_filter - http://php.net/manual/en/function.array-filter.php
explode - http://php.net/manual/en/function.explode.php
json_decode - http://php.net/manual/en/function.json-decode.php
Although this looks like a corrupt piece of JSON, I would say you can get the first car with explode().
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = explode("{", $string);
$firstcar = $string[1]; //your string starts with {, so $string[0] would be empty
$firstcar = explode(":", $firstcar);
$caryouarelookingfor = $firstcar[1]; // [0] would be 'car', [1] will be 'Toyota'
echo $caryouarelookingfor // output: "Toyota"
But, as also mentioned in the comments, the string looks like a corrupt piece of JSON, so perhaps you want to fix the construction of this string. :)
EDIT: typo in code, as said in first comment.

Categories