I have a string in a table field that looks like this:
part1=1,part2=S,part3=Y,part4=200000
To call it from the table I do this:
while($row = mysqli_fetch_array($result)) {
$row['mystring'];
}
My problem is that I need to separate the parts into variables for example:
From this:
part1=1,part2=S,part3=Y,someothername=200000
To This:
$part1 = '1';
$part2 = 'S';
$part3 = 'Y';
$someothername = '200000';
How can I do this?
Use like this
parse_str( str_replace(",", "&", "part1=1,part2=S,part3=Y,someothername=200000") );
Use with there name like:
$part1 // return 1
$part2 // return S
$part3 // return Y
works like you want, see the demo
First split string:
$s = "part1=1,part2=S,part3=Y,part4=200000";
$a = explode(",",$s);
then foreach part of string ("part1=1"...) create an array and explode as variable:
foreach($a as $k=>$v)
{
$tmp = explode("=",$v);
$tmp = array($tmp[0]=>$tmp[1]);
extract($tmp);
}
echo $part1;
If you use PHP 5.3+ you can use array_map
<?php
$string = 'part1=1,part2=S,part3=Y,part4=200000';
array_map(function($a){
$tmp = explode('=', $a, 2);
global ${$tmp[0]}; //make vars available outside of this function scope
${$tmp[0]} = $tmp[1];
}, explode(',', $string));
//Variables available outside of array_map scope
echo $part1 . '<br>';
echo $part2 . '<br>';
echo $part3 . '<br>';
echo $part4 . '<br>';
?>
Double explode your string to get the wanted field :
$string ="part1=1,part2=S,part3=Y,someothername=200000";
foreach (explode(',', $string) as $parts) {
$part = explode('=', $parts);
$array[$part[0]] = $part[1];
}
var_dump($array);
Output :
array(4) {
["part1"]=>
string(1) "1"
["part2"]=>
string(1) "S"
["part3"]=>
string(1) "Y"
["someothername"]=>
string(6) "200000"
}
I wouldn't suggest the use of variable variables to get the output as :
$part1 = ...
$part2 = ...
Using an array is probably the easier and safest way to do here. As suggested in my comment, it avoid potential conflicts with variable names.
You can use something called 'Variable variables'. You can declare the content of a variable as a variable, if you use double dollar sign, instead of a single one. For example:
$fruit = "apple";
$$fruit = "this is the apple variable";
echo $apple;
It would output the following:
this is the apple variable
You have to be a bit more tricky with defining variables from an array, as you'd have to enclode the original variable in curly brackets. (for example: ${$fruit[0]})
So the answer to your question is:
$parts = "part1=1,part2=S,part3=Y,someothername=200000";
$parts_array = explode(",", $parts);
foreach ($parts_array as $value) {
$temp = explode("=", $value);
${$temp[0]} = $temp[1];
}
echo "$part1, $part2, $part3, $someothername";
PHPFiddle link: http://phpfiddle.org/main/code/adyb-ug5n
Related
implode(',', $a);
I want to attach the $q variable in front of the $a so like this
implode(',', $q.$a);
But that doesn`t work. How can i put 2 variables in a implode function?
$a is an array with domain names like "com, org" and $q is the text (string) you type in before the domain names will appear.
I get the following error:
invalid argument passed in line..
Whole code:
$a = ['nl','net','com','co'];
$q = $_REQUEST["q"];
$domain = explode(".", $q);
$ext = #$domain[1] ?: ' ';
if (empty($ext)) {
echo implode(',',$a);
} else if (in_array($ext, $a)) {
echo $q;
} else {
$r = [];
foreach ($a as $x) {
if (strstr($x, $ext)) {
$r[] = $x;
}
}
echo (count($r)) ? implode(',',$r) : implode(',',$a);
}
If $a is an array and $q is the prefix string you can achieve that with 2 steps:
Add the prefix with:
$a = array("com", "co");
$q = "robot.";
foreach ($a as &$value)
$value = $q.$value;
Second, use the implode:
echo implode(',',$a);
output is:
robot.com,robot.co
Edited
I think this will be more suitable for you:
$a = array("com", "co", "org");
$q = "robot.c";
$arr = explode(".", $q);
$output = array();
foreach ($a as &$value) {
if (substr($value, 0, strlen($arr[1])) === $arr[1])
$output[]= $arr[0] . "." . $value;
}
echo implode(',',$output);
In this code you take the domain prefix and search for all domain name that may be fit for the prefix.
Notice that is this example we have domain org but he does not show up because your prefix is c
You need to add your $q before implode function. You can add your $q into your $a array using array_map function.
$array = array('com', 'org', 'net');
$q = 'test';
$array = array_map(function($value) {
$q= "test"; // you $q value goes here.
return $q.".".$value;
}, $array);
echo implode(',',$array);
Assuming that your business logic guarantees that $a is never empty, then here is the most direct, efficient, and concise technique...
Code: (Demo)
$a = ['nl', 'net', 'com', 'co'];
$q = 'example';
echo "$q." . implode(",$q.", $a);
Output:
example.nl,example.net,example.com,example.co
See how there is no need to loop or call any additional functions?
This basic technique of expanding the delimiting glue can be seen in other usages like:
echo '<tr><td>' . implode('</td><td>', $array) . '</td></tr>';
The idea is that you prepend what you need before the first value, then you declare the glue to be the characters that you need to occur after each value AND before the next value.
Merge an array with a string variable in PHP with the help of implode function
$a = array("com", "co");
$q = "robot.c";
$temp = explode(".",$q);
foreach ($a as $value)
echo $value = $temp[0].".".$value;
How to extract values from string seperated by |
here is my string
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
i need to store
$foo=1478
$boo=7854
$ccc=74125
Of course every body would suggest the explode route:
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
foreach(array_filter(explode('|', $var)) as $e){
list($key, $value) = explode('=', $e);
${$key} = $value;
}
Also, another would be to convert pipes to ampersand, so that it can be interpreted with parse_str:
parse_str(str_replace('|', '&', $var), $data);
extract($data);
echo $foo;
Both would produce the same. I'd stay away with variable variables though, it choose to go with arrays.
Explode the string by | and you will get the different value as array which is separated by |. Now add the $ before each value and echo them to see what you want.
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$arr = explode("|", $var);
$arr = array_filter($arr);
foreach($arr as $val){
echo "$".$val."<br/>";
}
You will get:
$foo=1478
$boo=7854
$bar=74125
$aaa=74125
$bbb=470
$ccc=74125
$ddd=1200
OR if you want to store them in the $foo variable and show only the value then do this:
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$arr = explode("|", $var);
$arr = array_filter($arr);
foreach($arr as $val){
$sub = explode("=", $val);
$$sub[0] = $sub[1];
}
echo $foo; //1478
You can use PHP variable variable concept to achieve your objective:
Try this:
<?php
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$vars=explode("|",$var);
foreach($vars as $key=>$value){
if(!empty($value)){
$varcol=explode("=",$value);
$varname=$varcol[0];
$varvalue=$varcol[1];
$$varname=$varvalue; //In this line we use $$ i.e. variable variable concept
}
}
echo $foo;
I hope this works for you....
You can use explode for | with array_filter to remove blank elements from array, and pass the result to array_map with a reference array.
Inside callback you need to explode again for = and store that in ref array.
there after use extract to create variables.
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$result = array();
$x = array_map(function($arr) use(&$result) {
list($key, $value) = explode('=', $arr);
$result[$key] = $value;
return [$key => $value];
}, array_filter(explode('|', $var)));
extract($result);
Use explode function which can break your string.
$array = explode("|", $var);
print_r($array);
I looked up some reference like this question and this question but could not figure out what I need to do.
What I am trying to do is:
Say, I have two strings:
$str1 = "link/usa";
$str2 = "link/{country}";
Now I want to check if this the pattern matches. If they match, I want the value of country to be set usa.
$country = "usa";
I also want it to work in cases like:
$str1 = "link/usa/texas";
$str2 = "link/{country}/{place}";
Maybe integers as well. Like match every braces and provide the variable with value. (And, yes better performance if possible)
I cannot get a work around since I am very new to regular expresssions. Thanks in advance.
It will give you results as expected
$str1 = "link/usa";
$str2 = "link/{country}";
if(preg_match('~link/([a-z]+)~i', $str1, $matches1) && preg_match('~link/{([a-z]+)}~i', $str2, $matches2)){
$$matches2[1] = $matches1[1];
echo $country;
}
Note: Above code will just parse alphabets, you can extend characters in range as per need.
UPDATE:
You can also do it using explode, see example below:
$val1 = explode('/', $str1);
$val2 = explode('/', $str2);
${rtrim(ltrim($val2[1],'{'), '}')} = $val1[1];
echo $country;
UPDATE 2
$str1 = "link/usa/texas/2/";
$str2 = "/link/{country}/{city}/{page}";
if(preg_match_all('~/([a-z0-9]+)~i', $str1, $matches1) && preg_match_all('~{([a-z]+)}~i', $str2, $matches2)){
foreach($matches2[1] as $key => $matches){
$$matches = $matches1[1][$key];
}
echo $country;
echo '<br>';
echo $city;
echo '<br>';
echo $page;
}
I don't see the point to use the key as variable name when you can built an associative array that will be probably more handy to use later and that avoids to write ugly dynamic variable names ${the_name_of_the_var_${of_my_var_${of_your_var}}}:
$str1 = "link/usa/texas";
$str2 = "link/{country}/{place}";
function combine($pattern, $values) {
$keys = array_map(function ($i) { return trim($i, '{}'); },
explode('/', $pattern));
$values = explode('/', $values);
if (array_shift($keys) == array_shift($values) && count($keys) &&
count($keys) == count($values))
return array_combine($keys, $values);
else throw new Exception ("invalid format");
}
print_r(combine($str2, $str1));
I have a variable, let's call it $var that echoes out something like:
32-Widgets: 18,28-Widgets: 24,57-Widgets: 45,44-Widgets: 24,55-Widgets: 45
The variable is created from a combination of a form submission and jQuery Sortables (which is why everything ends up in one variable, not two). The order is very important.
What I'd like to end up with is two variables (can be arrays) that would be:
$newVar1 = 32,18,24,45,24
$newVar2 = Widgets: 18,Widgets: 24,Widgets: 45,Widgets: 24,Widgets: 45
I started by:
$newVars = explode(",",$var);
But I'm at a loss of where to go from there. I've tried a variety of statements such as:
foreach ($newVars as $newVar) :
//Various explode() functions tried here.
endforeach;
If anybody has any idea what I'm missing I would certainly appreciate the help.
Thank you,
Eric
It's not very pretty, but it'll do the trick.
<?php
$str = "32-Widgets: 18,28-Widgets: 24,57-Widgets: 45,44-Widgets: 24,55-Widgets: 45";
$entries = explode(",", $str);
$parts1 = array();
$parts2 = array();
foreach ($entries as $e)
{
$temp = explode("-", $e);
$parts1[] = $temp[0];
$parts2[] = $temp[1];
}
print_r($parts1);
print_r($parts2);
?>
Running example: http://ideone.com/KkL06f
Have you tried something like this:
public function just_a_test() {
$var = "32-Widgets: 18,28-Widgets: 24,57-Widgets: 45,44-Widgets: 24,55-Widgets: 45";
$vars = explode(',', $var);
$partsA = $partsB = array();
foreach ($vars as $aVar) {
preg_match('/^(\d+)-(Widgets: \d+)$/i', $aVar, $parts);
$partsA []= $parts[0];
$partsB []= $parts[1];
}
echo '<pre>';
print_r($partsA);
print_r($partsB);
echo '</pre>';
}
You could easily end up with output like yours by calling the implode() with each array.
I have a string that contains elements from array.
$str = '[some][string]';
$array = array();
How can I get the value of $array['some']['string'] using $str?
This will work for any number of keys:
$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
$value = $value[$key];
echo $value
You can do so by using eval, don't know if your comfortable with it:
$array['some']['string'] = 'test';
$str = '[some][string]';
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));
$value = eval($code);
echo $value; # test
However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.
Another example if you need to write access to the array item, you can do the following:
$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
$value = &$value[$segment];
}
echo $value;
$value = 'changed';
print_r($array);
This is actually the same principle as in Eric's answer but referencing the variable.
// trim the start and end brackets
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];
I think regexp should do the trick better:
$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
if (isset($array[$keys['key1']][$keys['key2']]))
echo $array[$keys['key1']][$keys['key2']]; // do what you need
}
But I would think twice before dealing with arrays your way :D