php explode something into array, but using values in between - php

I have a string I want to clean up and put into an array so that I can search through it in mysql.
// Here's one example of what the string might have:
$string1 = "(1) *value1* *value2*; (2) *value3* *value4* *value5*; (3) *value6*";
// And here's another possibility:
$string2 = "*value1* *value2* *value3* *value4*";
// I want to remove all the "(#)" stuff, and explode all the values into an array
// This is what I have so far:
// $string can be like the examples $string1 or $string2
$string_clean = str_replace("* *","",trim(preg_replace("/\((\d)\)/i", "", $string)));
$my_array = explode('*', trim($string_clean, '*'));
However, this is what I'm getting:
Array ( [0] => value1 [1] => [2] => value2 [3] => [4] => value3 [5] => [6] => value4 [7] => [8] => value5 )
I suppose I could just find a function to remove all empty items from the array, but I'm wondering if there's a more effective way to do this?

You need preg_match_all():
preg_match_all('#\*([^*]+)\*#', $string, $matches);
$result = $matches[1];
// $result is array('value1', 'value2', ...)
This will find all *something* and return the strings between the *.

Related

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
)

Add <br /> after 3rd symbol in Array

I have the following variable:
$checkbox = implode(';', $_POST['product']);
$checkbox is equal to "Product Name;Price;Unit", how can I add a break after every line?
At the moment $checkbox is equal to:
ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1
I need it to be like:
ASFP4040;18.95;1;
ASFP4048;21;1;
ASGS100100;25.45;1;
EDIT:
I am writing this to a .TXT file, \n shows as text and doesn't actually create a new line.
As I'm not sure, how your $_POST['products'] var looks like, you might like one of these options:
If you have everything in a single array element like this
Array
(
[0] => ASFP4040
[1] => 18.95
[2] => 1
[3] => ASFP4048
[4] => 21
[5] => 1
[6] => ASGS100100
[7] => 25.45
[8] => 1
)
you could split the array into chunks and join them together
$data = implode("\n", array_map(function($chunk) {
return implode(';', $chunk);
}, array_chunk($_POST['product'], 3)));
Alternatively, if you have an array of strings like below:
Array
(
[0] => ASFP4040;18.95;1
[1] => ASFP4048;21;1
[2] => ASGS100100;25.45;1
)
a simple implode would be enough
$data = implode("\n", $_POST['product']);
Try this:
echo "'".implode("','",$checkbox)."'<br>";
You can use regular expressions to do this. Just replace my $str with your $checkbox.
$str = 'ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1';
$str2 = preg_replace('/((?:(?:[^;]+);){3})/',"$1\n",$str);
echo $str2;
As explained in Magnus Eriksson's comment and mine, you just have to use "\n" as first parameter of your implode:
$checkbox = implode("\n", $_POST['product']);
Please notice the use of double quotes (") in order for \n to be used as a linebreak.

Transfer list in php in another list

I have a list of words for example this one
$words1="Les voitures Le compteur principal capteurs(gaz et l'éclairage) l'humidité L'extérieur"
and i want to have the list like this:
$words2="Les","voitures","Le","compteur","principal","capteurs(gaz","et","l'éclairage)","l'humidité","L'extérieur"
i did the split a string by string of the list using explode and then i did not find how to add the "," between the strings:
$text_list =explode(" ",$words1);
Try this: Online Test
First explode the string as " ", and then implode the using " , " and also add the " before and after implode.
$text_list = explode(" ",$words1);
echo $words2 = '"'.implode('","', $text_list).'"';
you will get:
"Les","voitures","Le","compteur","principal","capteurs(gaz","et","l'éclairage)","l'humidité","L'extérieur"
As per your requirement:
$words2 = explode(",", '"'.implode('","', $text_list).'"');
echo gettype($words2); //array
print_r of $words2:
Array
(
[0] => "Les"
[1] => "voitures"
[2] => "Le"
[3] => "compteur"
[4] => "principal"
[5] => "capteurs(gaz"
[6] => "et"
[7] => "l'éclairage)"
[8] => "l'humidité"
[9] => "L'extérieur"
)
Another way:
$words2 = array('"'.implode('","', $text_list).'"');
echo gettype($words2); //array
print_r of $words2:
Array
(
[0] => "Les","voitures","Le","compteur","principal","capteurs(gaz","et","l'éclairage)","l'humidité","L'extérieur"
)
If you're trying to make an array from the string, your approach is valid - just use the explode() function. But if you're trying to replace the space in the string with commas, you can use the str_replace() function.
$words1="Les voitures Le compteur principal capteurs(gaz et l'éclairage) l'humidité L'extérieur";
$commaSeparatedString = str_replace(' ', ', ', $words1);
Further, you can explode the result by space, to get each word with comma in a simple array.
$result = explode(' ', $commaSeparatedString);

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

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