I'm using PHP, and I get a string from a db with a struct similar to this:
$string = "a:b;c:d;e:f;g:h;" and so on, where a, b, c.. are variables,
a,c and e couldn't be a continuous number, they can be numbers from 1 to 500.
I need to convert this string into an array with this format:
$array [a] == ("b");
$array [c] == ("d");
$array [e] == ("f");
etc...
But I don't know how to get two substring from string (double dot separated, and dot comma separated) and put it into a 2 D string.
Thanks you in advance
To manipulate the keys and the values of the resulting array without foreach loop, you can use array_reduce:
$string = "a:b;c:d;e:f;g:h;";
$array = array_reduce( array_filter( explode( ';', $string ) ), function( $result, $item ) {
$tmp = explode( ':', $item );
$result[$tmp[0]] = $tmp[1];
return $result;
});
output:
Array (
[a] => b
[c] => d
[e] => f
[g] => h
)
not sure what you are asking,but this may helps you
$re = '/(.?):(.?)/';
$str = 'a:b;c:d;e:f;g:h;';
preg_match_all($re, $str, $matches);
print_r(array_combine($matches[1],$matches[2]));
output:
(
[a] => b
[c] => d
[e] => f
[g] => h
)
use explode() which will split a string into an array based on the specified delimiter.
$string = "a:b;c:d;e:f;g:h;";
$temparray = explode(';', $string);
//$temparray now looks like ['a:b', 'c:d', 'e:f']
//use explode() again in a loop to split up each index
$finalarray = array();
foreach($temparray as $arr){
$splitarr = explode(':', $arr);
//$splitarr will look something like ['a', 'b']
//use those values to set the indexes in your final array
$finalarray[$splitarr[0]] = $splitarr[1];
}
$finalarray=array_filter($finalarray);//to remove null values
//print_r($finalarray);
NOTE: Just FYI, because of the trailing ; in your string, you may end up with an extra empty index at the end of your arrays, hence the array_filter() call, thanks #FerozAkbar
Related
Suppose I have a string (which contain array of objects):
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
My goals is to get the output to look like this when I print_r:
Array
(
[0] => Array
(
[test] => 1
[anothertest] => 2
)
[1] => Array
(
[test] => 3
[anothertest] => 4
)
)
I tried to json_decode($string) but it returned NULL
Also tried my own workaround which is kinda solved the problem,
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = substr($string, 1, -1);
$string = str_replace("'","\"", $string);
$string = str_replace("},","}VerySpecialSeparator", $string);
$arrayOfString = explode("VerySpecialSeparator",$string);
$results = [];
foreach($arrayOfString as $string) {
$results[] = json_decode($string, true);
}
echo "<pre>";
print_r($results);
die;
But is there any other ways to solve this?
As per your given data, if quotes will be corrected, then you will get your desired output, so get it done like below:
<?php
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = str_replace("'",'"', $string);
print_r(json_decode($string,true));
https://3v4l.org/PDI7O
I have a string that looks like this:
"illustration,drawing,printing"
I have an array that looks like this:
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
How can I compare the two and only display the terms that exist in both the string and array?
So in the above example, I would want to output something that looks like this:
SKILLS: illustration, drawing
Thank you!
use explode(), array_intersect() and implode()
<?php
$string = "illustration,drawing,printing";
$array = Array (
0 => 'illustration',
1 => 'drawing',
2 => 'painting',
3 => 'ceramics'
);
$stringArray = explode(',',$string);
$common = array_intersect($stringArray,$array);
echo "Skills :".implode(',',$common);
https://3v4l.org/StqYN
You can do something like this:
Function:
function functionName($string, $array){
$skills = '';
// Create a temp array from your string breaking appart from the commas
$temparr = explode(",", $string);
// Iterate through each of the words now
foreach($temparr as $str){
// Check to see if our current string is in the array provided
if(in_array($str, $array)){
// If it is, then add it to the string "skills"
$skills .= "${str}, ";
}
}
// Cut the last space and comma off the end of the str.
$skills = substr($skills, 0, strlen($skills) - 2);
// Return our results
return 'SKILLS: '.$skills;
}
Usage:
$string = "illustration,drawing,printing";
$array = Array (
0 => "illustration",
1 => "drawing",
2 => "painting",
3 => "ceramics"
);
// Just input our string and the array we want to search through
echo(functionName($string, $array));
Live Demos:
https://ideone.com/qyqgzo
http://sandbox.onlinephpfunctions.com/code/65dc988370ad8ce61ab5ccbc232af4bcf8bd3d42
You could replace the comma , and join the string words on OR | and grep for them. This will match the word anywhere in each array element:
$result = preg_grep("/".str_replace(",", "|", $string)."/", $array);
If you want exact matches only then: "/^(".str_replace(",", "|", $string).")$/"
Firstly convert that string into array.
use array_intersect();
$str = "illustration,drawing,printing";
$ar1 = explode(",",$str);
print_r ($ar1);
$ar2 = Array ("illustration","drawing","painting","ceramics");
echo "<br>";
print_r ($ar2);
$result = array_intersect($ar1, $ar2);
echo "Skills :".implode(',',$result);
OUTPUT:
Array (
[0] => illustration
[1] => drawing
[2] => printing
)
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
SKILLS: illustration, drawing
I have a string in the following form:
$my_original_string = "A value1,A value2,E value3,A value4";
The first letter is a sort of label, the value is associated with a label.
I must manipulate and convert my string to the following:
$my_converted_string = "A: value1 value2 value4, E: value3";
With a simple loop, I created an array $temp:
$my_original_string = "A value1,A value2,E value3,A value4";
$original_string_to_array = explode(",", $my_original_string);
$o_len = count($original_string_to_array);
$temp = [];
for($i=0; $i<$o_len; $i++){
$temp[explode(" ",$original_string_to_array[$i])[0]][] = explode(" ",$original_string_to_array[$i])[1];
}
print_r($temp);
/*
Result:
Array
(
[A] => Array
(
[0] => value1
[1] => value2
[2] => value4
)
[E] => Array
(
[0] => value3
)
)
*/
Starting from here, I could eventually loop again to build my new string. Or maybe I could do it even in one loop.
But, is there anything better I could do? I checked the capabilities of array_map, array_filter and array_walk but I could not find a way to apply them in this particular case.
Thanks in advance.
A couple of coding improvements would reduce some of the code, using a foreach instead of the for (where you also have to count the items). Also inside the loop, use explode() once to reduce repetition of the code.
This also inside the loop checks if the key is already present. If it is, it just appends the new value, if it isn't it creates a new value with the key and value. When it outputs the value, it uses implode() to stick the values back together...
$my_original_string = "A value1,A value2,E value3,A value4";
$originalArray = explode(",", $my_original_string);
$output = [];
foreach($originalArray as $item ) {
[$key, $value] = explode(" ", $item, 2);
$output[$key] = (isset($output[$key])) ? $output[$key]." ".$value
: "$key: $value";
}
print_r(implode(", ", $output));
gives...
A: value1 value2 value4, E: value3
Although you can use array_map
$string = "A value1,A value2,E value3,A value4,B value5";
$split = explode(',', $string);
$walk = array();
$map = array_map(function($a) use(&$walk) {
list($key,$value) = explode(' ',$a);
$walk[$key] = (isset($walk[$key]) ?
sprintf('%s %s',$walk[$key],$value)
: sprintf('%s: %s',$key,$value));
return $walk;
}, $split);
$str = implode(',',array_pop($map));
echo $str;
return output with :
A: value1 value2 value4,B: value5,E: value3
or in array
Array
(
[A] => A: value1 value2 value4
[B] => B: value5
[E] => E: value3
)
Note: if you use $map you need to use array_pop to get last element, also you can use $walk if you don't like to use array_pop
I have $value = "10,120,152" in string, now i want to put each number in separate variable like $a = 10; $b = 120; $c = 152;
so basically what i am asking is that how to separate , from the numbers in a string.
If the separator is always a , than using explode makes sense. If the separator varies though you could use a regex.
$value = "10,120,152";
preg_match_all('/(\d+)/', $value, $matches);
print_r($matches[1]);
Output:
Array
(
[0] => 10
[1] => 120
[2] => 152
)
Demo: https://eval.in/483906
That \d+ is all continuos numbers.
Regex101 Demo: https://regex101.com/r/rP2bV1/1
A third approach would be using str_getcsv.
$value = "10,120,152";
$numbers = str_getcsv($value, ',');
print_r($numbers);
Output:
Array
(
[0] => 10
[1] => 120
[2] => 152
)
Demo: https://eval.in/483907
$exploded = explode("," , $values);
var_dump($exploded);
Explode(string $delimiter , string $string [, int $limit ])
You can use explode(), it will return an array with the numbers.
$array = explode(',', $value);
Check this one using list
$value = "10,120,152";
$variables = explode("," , $values);
$variables = array_map('intval', $variables);//If you want integers add this line
list($a, $b, $c) = $variables;
I have this variable:
$str = "w15";
What is the best way to split it to w and 15 separately?
explode() is removing 1 letter, and str_split() doesn't have the option to split the string to an unequal string.
$str = "w15xx837ee";
$letters = preg_replace('/\d/', '', $str);
$numbers = preg_replace('/[^\d]/', '', $str);
echo $letters; // outputs wxxee
echo $numbers; // outputs 15837
You could do something like this to separate strings and numbers
<?php
$str = "w15";
$strarr=str_split($str);
foreach($strarr as $val)
{
if(is_numeric($val))
{
$intarr[]=$val;
}
else
{
$stringarr[]=$val;
}
}
print_r($intarr);
print_r($stringarr);
Output:
Array
(
[0] => 1
[1] => 5
)
Array
(
[0] => w
)
If you want it to be as 15 , you could just implode the $intarr !
Use preg_split() to achieve this:
$arr = preg_split('~(?<=\d)(?=[a-zA-Z])|(?<=[a-zA-Z])(?=\d)~', $str);
Output:
Array
(
[0] => w
[1] => 15
)
For example, the string w15g12z would give the following array:
Array
(
[0] => w
[1] => 15
[2] => g
[3] => 12
[4] => z
)
Demo
Much cleaner:
$result = preg_split("/(?<=\d)(?=\D)|(?<=\D)(?=\d)/",$str);
Essentially, it's kind of like manually implementing \b with a custom set (rather than \w)