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.
Related
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
)
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"
)
)
i want to get a particular value from string in php. Following is the string
$string = 'users://data01=[1,2]/data02=[2,3]/*';
preg_replace('/(.*)\[(.*)\](.*)\[(.*)\](.*)/', '$2', $str);
i want to get value of data01. i mean [1,2].
How can i achieve this using preg_replace?
How can solve this ?
preg_replace() is the wrong tool, I have used preg_match_all() in case you need that other item later and trimmed down your regex to capture the part of the string you are looking for.
$string = 'users://data01=[1,2]/data02=[2,3]/*';
preg_match_all('/\[([0-9,]+)\]/',$string,$match);
print_r($match);
/*
print_r($match) output:
Array
(
[0] => Array
(
[0] => [1,2]
[1] => [2,3]
)
[1] => Array
(
[0] => 1,2
[1] => 2,3
)
)
*/
echo "Your match: " . $match[1][0];
?>
This enables you to have the captured characters or the matched pattern , so you can have [1,2] or just 1,2
preg_replace is used to replace by regular expression!
I think you want to use preg_match_all() to get each data attribute from the string.
The regex you want is:
$string = 'users://data01=[1,2]/data02=[2,3]/*';
preg_match_all('#data[0-9]{2}=(\[[0-9,]+\])#',$string,$matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => data01=[1,2]
[1] => data02=[2,3]
)
[1] => Array
(
[0] => [1,2]
[1] => [2,3]
)
)
I have tested this as working.
preg_replace is for replacing stuff. preg_match is for extracting stuff.
So you want:
preg_match('/(.*?)\[(.*?)\](.*?)\[(.*?)\](.*)/', $str, $match);
var_dump($match);
See what you get, and work from there.
I have a string
$str = "recordsArray[]=3&recordsArray[]=1";
Is there any simple way to make this to an array other than exploding
this string at &? Im expecting a result like this print_r($str);
//expecting output
array('0' => '3','1' => '1');
Yes there is: parse_strDocs; Example (Demo):
parse_str("recordsArray[]=3&recordsArray[]=1", $test);
print_r($test);
Use preg_match_all like this:
$str = "recordsArray[]=3&recordsArray[]=1";
if ( preg_match_all('~\[\]=(\d+)~i', $str, $m) )
print_r ( $m[1] );
OUTPUT:
Array
(
[0] => 3
[1] => 1
)
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 *.