php parsing comma separated list of var=value pairs - php

I'm receiving a string
a=100,b=20,c=20;
for instance I know exploding this into an array using , as delimiter,
and it becomes
a=100
b=20
c=20
as strings,
how can this be further evaluated as variables inside php so I could do
echo $a //100
echo $b //20
echo $c //20

try the function "parse_str",like
$str = str_replace(',','&',"a=100,b=10,c=20");
parse_str($str);
echo $a;
echo $b;
echo $c;

$string = 'a=1,b=20,c=43';
foreach ( explode(',', $string) as $expression ) {
list($variable,$value) = explode('=', $expression);
$$variable = $value;
}
echo 'a = ', $a, ' and b = ', $b, ' and c = ', $c, PHP_EOL;
Cheers

Depends how "dangerous" you want everything to be - you can always use eval but then there are many issues to take into consideration.
Example:
eval("\$str = \"test\";");
echo $str;

Try This
$input = 'a=100,b=20,c=20';
$items = explode(',',$input);
foreach($items as $i){
$pair = explode('=',$i);
$$pair[0] = $pair[1];
}

$input = 'a=100,b=20,c=20';
$statements = explode (',', $input);
foreach ($statements as $s)
eval ('$' . $s); // THIS IS EVIL!!!! TOO MANY SECURITY PROBLEMS
echo $a; // will output 100
echo $b; // will output 20
echo $c; // will output 20

You can use variable names for variables. Take for example:
$var = 'var2';
$$var = 5;
echo $var2;
this echoes 5 to the command line.
$var evaluates to being var2, and $var2 is set to 5.
Taking your code we can create this:
$string = 'a=100,b=20,c=20';
$array = explode(',',$string);
foreach($array as $element) {
$temp = explode('=',$element);
$$temp[0] = $temp1;
}
echo $a.' '.$b.' '.$c;
This echoes the string '100 20 20'.

Related

Build string on one line PHP

I want to build a combination of numbers and letters separated by - (minus sign). i.e 1-R-3. The first number are in an array called $Points ,the letters are stored in a array called $Color and the last number is in a third array called $Points2;
$Points = [1,2,3,4];
$Color = [R,B,V,Y];
$Points = [1,2,3,4];
I want the result to be one one row 1-R-1, 2-B-2 and so on. Now the result outputs as:
1
(minus sign)
R
(minus sign)
3
`
$Bind = "-";
$foo = $Points[0] . $Bind . $Points[1];
I have tried to convert the integer to a string by (String) but have not worked.
Can somebody help me to get the result on one line? I bet i'm missing something easy!
EDIT: The format in the arrays where incorrect since I forgot ->plaintext when doing my web-scraping.
/U
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
foreach ($Points as $point=>$value) {
echo $value . '-' . $Color[$point] . '-' . $value . PHP_EOL;
}
Note that the values in the $Color array need to be in quotes to avoid errors.
You have two arrays called $Points, so I've renamed one.
This just combines the three arrays by using foreach and using the key of each element and using it to access the other arrays at the same index...
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points1 = [1,2,3,4];
$bind = "-";
foreach ( $Points as $key => $val ) {
echo $val.$bind.$Color[$key].$bind.$Points1[$key].PHP_EOL;
}
This may be occurring because of the tabs or carriage return:
<?php
$points = [1,2,3,4];
$colors = ['R','B','V','Y'];
$bind = '-';
$foo = [];
for ($x = 0; $x <= 3; $x++) {
$foo[$x] = $points[$x].$bind.$colors[$x].$bind.$points[$x];
}
foreach($foo as $value) {
echo $value.'<br>';
}
?>
Result:
1-R-1
2-B-2
3-V-3
4-Y-4
You can use php join function. For example:
$results = [];
for ($i = 0; $i < count($Points); $i++) {
$results[] = join('-', [$Points[$i], $Colors[$i], $Points2[$i]]);
}
// Now you have your combined values in $results array
var_export($results);
You can combine array into one string like
<?php
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points = [1,2,3,4];
$result='';
$bind='-';
foreach ($Points as $index => $value) {
$result .= $value .$bind . $Color[$index] . $bind . $value.PHP_EOL;
}
echo $result;
?>
DEMO

How do i turn an string into variables and still get a good output

How do i turn an string into variables and still get a good output.
$text = "showandreturn";
$disp = str_split($text, 2);
$firstnum = 3;
for($b = 0; $b<$firstnum; $b++){
$a = "$disp[$b]"; #showan
}
$b = "ENDED";
for($b = $firstnum; $b<sizeof($disp); $b++){
$c = "$disp[$b]"; #dreturn
echo = "$a$b$c";
}
my current output with this code is . andranetanurann ..
And I want beter result like showanENDEDdreturn
Thanks for your time and understanding..
Are you trying to put ENDED in the middle of the string?
In that case have a look at this:
$text = "showandreturn";
$b = "ENDED";
$len = strlen($text); // lenght of string
// Output half string + $b + rest of string
Echo substr($text, 0, floor($len/2)) . $b . substr($text, floor($len/2));
https://3v4l.org/Ea6tn
You are overwriting your variables every time it loops so only the result of the last loop is stored in the variable.
This code should return the required output.
$text = "showandreturn";
$disp = str_split($text, 2);
$num = 3;
$a = '';
$c = '';
for($b = 0; $b<$num; $b++){
$a .= $disp[$b];
}
$b = "ENDED";
for($bn = $num; $bn<sizeof($disp); $bn++){
$c .= $disp[$bn];
}
echo $a.$b.$c;
Alternative 1
What you need is variables variable
$foo = 'bar';
$foo = 'magic';
echo $foo; //Outputs magic
Alternative 2:
you can check http://php.net/manual/en/function.parse-str.php
parse_str($"My Value=Something");
echo $My_Value; // Something
Alternative 3:
echo eval('return $'. $string . ';');

Get step step url in url string of PHP

Lets say i have url like this
$a= "http://zz.com/1/2/3/4/5/6/7";
say that url can have many step like 1 ,2 ,3 say something it have up to 3 or sometime up to 7
I want to get url like this from $a
$b="http://zz.com/";
$c="http://zz.com/1/";
$d="http://zz.com/1/2/";
$e="http://zz.com/1/2/3/";
...
...
$k= "http://zz.com/1/2/3/4/5/6/;
Is it possible to do such things in php?
Thank you very much .
I tried to use php url parse and explode but get empty value in beginning and end of array.
Very simple way is to use explode() function.
[EDIT] made it use letters as variables if that was necessary
$a= "http://zz.com/14/2/13/4/5/8/7";
//grab the protocol and addy
$x = explode('//',$a);
$y = explode('/',$x[1]);
$letters = array();
$letters[1] = 'a';
$letters[2] = 'b';
$letters[3] = 'c';
$letters[4] = 'd';
$letters[5] = 'e';
$letters[6] = 'f';
$letters[7] = 'g';
$letters[8] = 'h';
$letters[9] = 'i';
$letters[10] = 'j';
//loop through various steps
for($i = 1; $i<=count($y); $i++)
{
$$letters[$i] = $x[0].'//'.$y[0].'/';
for($k=0; $k<$i; $k++)
{
$$letters[$i] .= $y[$k].'/';
}
}
echo $a."\n";
echo $b."\n";
echo $c."\n";
echo $d."\n";
echo $e."\n";
echo $f."\n";
echo $g."\n";
echo $h."\n";
that will output:
http://zz.com/zz.com/
http://zz.com/zz.com/14/
http://zz.com/zz.com/14/2/
http://zz.com/zz.com/14/2/13/
http://zz.com/zz.com/14/2/13/4/
http://zz.com/zz.com/14/2/13/4/5/
http://zz.com/zz.com/14/2/13/4/5/8/
http://zz.com/zz.com/14/2/13/4/5/8/7/
You can see the code working here: http://sandbox.onlinephpfunctions.com/code/4c0446acaf0fd298fc089b743da5a807529e3e0b
[EDIT: with letters here]http://sandbox.onlinephpfunctions.com/code/bb655992fa81f0005938d86697e91272dc57425a
you can try this code:-
<?php
$a= $_SERVER['REQUEST_URI'];//"http://zz.com/1/2/3";
$url = explode('/',str_replace('http://', '', $a));
$next_num = count($url);
echo $next_url = $a.'/'.$next_num;//wil print :- http://zz.com/1/2/3/4
?>
Yes you can and it is pretty easy and it is good to use build in function called parse_url() which extracts some parts of URL.
$url = "http://zz.com/1/2/3/4/5/6/7";
$pathvars = parse_url($url);
$urls = [];
$glue = '';
$counter = 'a';
foreach ($path as $part) {
$glue .= "$part/";
$urls[$counter++] = sprintf("%s://%s%s", $pathvars['scheme'], substr($pathvars['host'], 0, strlen($pathvars['host']) -1), substr($glue, 0, strlen($glue) - 1));
}
// extract to variables
extract($urls, EXTR_OVERWRITE);
echo $a . PHP_EOL;
echo $b . PHP_EOL;
echo $c . PHP_EOL;
echo $d . PHP_EOL; // etc
print_r($urls); // all array of urls

php the best way to split string containing pairs of values

i have a string in the following format:
$str='a1_b1,a2_b2,a3_b3'
where a and b - some positive numbers. i need to split it to get two strings in format:
'a1,a2,a3' and 'b1,b2,b3'
the very primitive way would be:
$temp=explode(',', $str);
$str1='';
$str2='';
for($i=0;$i<count($temp);$i++){
$temp2=explode('_',$temp[$i]);
$str1.=$temp2[0].',';
$str2.=$temp2[1].',';
}
is it possible to do it more intelligent then just explode in loop?
Not much different from accepted answer but doing it with fewer code
<?php
$str = 'a1_b1,a2_b2,a3_b3';
$temp=explode(',', $str);
foreach($temp as $tem)
list($str_a[], $str_b[])=explode('_',$tem);
$str1 = implode(',', $str_a);
$str2 = implode(',', $str_b);
Probably the easiest way (which also happens to use the least amount of code and no loops) is to make use of PHP's parse_str() function:
// Assuming $str = 'a1_b1,a2_b2,a3_b3'
$str = str_replace([',', '_'], ['&', '='], $str);
parse_str($str, $arr);
// Your key/value pairs are now in $arr
$keys = implode(',', array_keys($arr));
$values = implode(',', array_values($arr));
Of course, parse_str() expects the standard foo=bar&baz=boz format, so if possible, you should use that format instead of foo_bar,baz_boz to save yourself a step. But, if that's not possible, then you can simply use str_replace() like I did above to make the appropriate substitutions.
Note: I used PHP 5.4 short array syntax [...]. If you're using < PHP 5.4, change it to array(...) instead.
The best way would be to organize the formatting of the string so that it doesnt come to this stage where you need to do this. But I'm assuming that you cant do that, therefore posting this question here,
What you did is a good way to do this unless you want to use regex.
$str = 'a1_b1,a2_b2,a3_b3' ;
$exp = explode(',', $str);
$a = array();
$b = array();
foreach($exp as $i)
{
$sep = explode('_', $i);
$a[] = $sep[0];
$b[] = $sep[1];
}
// at this point a and b are arrays so if you want to do better things to the data
// you can use arrays instead of manually concatenating the items with commas
$a_str = implode(',', $a); // a1,a2,a2
$b_str = implode(',', $b); // b1,b2,b2
$temp=explode(',', $str);
$str1='';
$str2='';
$str_a = array();
$str_b = array();
for($i=0;$i<count($temp);$i++){
$temp2=explode('_',$temp[$i]);
$str_a[]=$temp2[0];
$str_b[]=$temp2[1];
}
$str1 = implode(',', $str_a);
$str2 = implode(',', $str_b);
Oh, this is nothing more intelligent...
I can't really think of a better way of doing it. The best thing would be to not get in a situation where you need to do this in the first place but what can we do?
Just to provide another (not better) way of doing the same thing, you can use strtok.
$str='a1_b1,a2_b2,a3_b3';
$tok = strtok($str, "_,");
$i = 0;
$a = array();
$b = array();
while ($tok !== false) {
if ($i++ %2) $b[] = $tok;
else $a[] = $tok;
$tok = strtok("_,");
}
echo implode(',', $a); //a1,a2,a3
echo implode(',', $b); //b1,b2,b3
Your way is more clear and easier to understand, so I'd just stick with it.
Assuming PHP >= 5.3.0:
$str = 'a1_b1,a2_b2,a3_b3';
$array = array_map(function($n) { return explode("_", $n); }, explode(",", $str));
$aString = implode(",", array_map(function($n) { return $n[0]; }, $array));
$bString = implode(",", array_map(function($n) { return $n[1]; }, $array));
var_dump($aString);
var_dump($bString);
Output:
string 'a1,a2,a3' (length=8)
string 'b1,b2,b3' (length=8)
Still looping strictly speaking, but fancier :)
$str = 'a1_b1,a2_b2,a3_b3' ;
$arr = preg_split("/[\s,_]/" , $str);
$str1 = $str2 = '';
for($i=0; $i<count($arr); $i++) {
$str1 .= $arr[$i] ;
if(isset($arr[$i+1]))
$str2 .= $arr[$i+1];
if(isset($arr[$i+2])) {
$str1 .= ',';
$str2 .= ',';
}
$i++;
}

Modify numbers inside a string PHP

I have a string like this:
$string = "1,4|2,64|3,0|4,18|";
Which is the easiest way to access a number after a comma?
For example, if I have:
$whichOne = 2;
If whichOne is equal to 2, then I want to put 64 in a string, and add a number to it, and then put it back again where it belongs (next to 2,)
Hope you understand!
genesis'es answer with modification
$search_for = 2;
$pairs = explode("|", $string);
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
//do whatever you want here
//for example:
$numbers[1] += 100; // 100 + 64 = 164
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
$numbers = explode("|", $string);
foreach ($numbers as $number)
{
$int[] = intval($number);
}
print_r($int);
$string = "1,4|2,64|3,0|4,18|";
$coordinates = explode('|', $string);
foreach ($coordinates as $v) {
if ($v) {
$ex = explode(',', $v);
$values[$ex[0]] = $ex[1];
}
}
To find the value of say, 2, you can use $whichOne = $values[2];, which is 64
I think it is much better to use the foreach like everyone else has suggested, but you could do it like the below:
$string = "1,4|2,64|3,0|4,18|";
$whichOne = "2";
echo "Starting String: $string <br>";
$pos = strpos($string, $whichOne);
//Accomodates for the number 2 and the comma
$valuepos = substr($string, $pos + 2);
$tempstring = explode("|", $valuepos);
$value = $tempstring[0]; //This will ow be 64
$newValue = $value + 18;
//Ensures you only replace the index of 2, not any other values of 64
$replaceValue = "|".$whichOne.",".$value;
$newValue = "|".$whichOne.",".$newValue;
$string = str_replace($replaceValue, $newValue, $string);
echo "Ending String: $string";
This results in:
Starting String: 1,4|2,64|3,0|4,18|
Ending String: 1,4|2,82|3,0|4,18|
You could run into issues if there is more than one index of 2... this will only work with the first instance of 2.
Hope this helps!
I know this question is already answered, but I did one-line solution (and maybe it's faster, too):
$string = "1,4|2,64|3,0|4,18|";
$whichOne = 2;
$increment = 100;
echo preg_replace("/({$whichOne},)(\d+)/e", "'\\1'.(\\2+$increment)", $string);
Example run in a console:
noice-macbook:~/temp% php 6642400.php
1,4|2,164|3,0|4,18|
See http://us.php.net/manual/en/function.preg-replace.php

Categories