below is the code I have created. My point here is to convert all strings inside the function argument.
For example, fname('variable1=value1&variable2=value2'); I need to convert variable1 & variable2 into ang variable as $variable1, $variable2 instead parsing a plain text. I found out eval() function is useful but it only takes one string which is the "variable1" and its value.
function addFunction($arg){
echo eval('return $'. $arg . ';');
}
addFunction('variable1=value1&variable2=value2');
Now the problem is I got this error "Parse error: syntax error, unexpected '=' in D:\xampp\htdocs...\index.php(7) : eval()'d code on line 1". But if I have only one variable and value inside the function argument it works perfect, but I need to have more parameters here. Is this possible to do this thing or is there any other way to count the parameters before it can be evaluated?
Thank you,
function addFunction($arg)
{
parse_str($arg, $args);
foreach ($args as $key => $val) {
echo $key , " --> " , $val, "\n";
}
}
addFunction('variable1=value1&variable2=value2');
Output
variable1 --> value1
variable2 --> value2
You can also use
function addFunction($arg)
{
parse_str($arg);
echo $variable2; // value2
}
addFunction('variable1=value1&variable2=value2');
You are trying to create a variable with this name:
$variable1=value1&variable2=value2
You need to explode it at the & to get just the desired future variable names.
function addFunction($arg){
echo eval('return $'. $arg . ';');
}
$string = 'variable1=value1&variable2=value2';
$array = explode('&', $string);
foreach($array as $part)
{
addFunction($part);
}
You can break a string up using the PHP explode function, and then use eval to evaluate each variable indepedently.
$myvars = explode ('$', 'variable1=value1&variable2=value2');
$myvars is then an array which you can parse and feed to eval as needed.
Perhaps you can use explode()?
$varArr = explode("&",$arg);
foreach ($varArr as $varKey=>$varVal) {
echo eval('return $'.$varKey.'='.$varVal.';');
}
You need split the $arg at & to get each variable and then again at = to get each variable and value.
$arg = 'variable1=value1&variable2=value2';
$vars = explode('&', $arg);
foreach ($vars as $var) {
$parts = explode("=", $var);
echo eval('return $'. $parts[0] . '='. $parts[1] . ';');
}
Something like this:
function addFunction($arg)
{
$varArr = explode("&",$arg);
$varResponse ="";
foreach ($varArr as $varKey=>$varVal) {
$varResponse = $varResponse."$".$varVal.";";
}
return $varResponse;
}
echo addFunction('variable1=value1&variable2=value2');
Saludos ;)
Related
I Want change all Strings starting with {" and ending with "} to a variable,
for example:
Hello {username}, -> to Hello $array['username']
Your Country is {country}, -> Your Country is $array['country']
But i get all strings text from database with one variable (Mysql) With $array['content']
What I Want:
str_replace("{$whatinhere}",$array['$copytohere'],$array['content']);
str_replace("{company}",$array['company'],$array['content']);
Use preg_replace_callback function
echo preg_replace_callback('~{(.+?)}~',
function($x) use ($array) { return isset($array[$x[1]]) ? $array[$x[1]] : ''; },
$array['content']);
I think you should try this...
$content = $array['content'];
$mainContent = str_replace('{username}', $array['username'], $content);
$mainContent = str_replace('{company}', $array['company'], $mainContent);
echo $mainContent;
As I understand the $array variable contains the placeholder key/value pairs and also the content. You can try following code for replacing all placeholder keys with their corresponding values:
foreach ($array as $key => $value) {
if ($key != "content") {
$array["content"] = str_replace("{" . $key . "}", $value, $array["content"]);
}
}
/** Print contents */
echo $array["content"];
I have array of 3000 elements which are like this
Array[0]= 405adc92-cfad-4be6-9ad2-ca363eda4933
Array[1]= 405adc92-cfad-4be6-9ad2-ca363eda4933
And I need to pass a variable in a function which require only a single quote at the beginning. I tried a solution on web which is pasting single quote on beginning and end aswell .like this
function add_quotes($str) {
return sprintf("'%s'", $str);
}
$csv = implode(',', array_map('add_quotes', $a));
$myArray = explode(',', $csv);
echo gettype($myArray[1]);
so answer is like this
myArray[1]='405adc92-cfad-4be6-9ad2-ca363eda4933'
So what Could I do to get rid ?
could you not just add the ' at the beginning of each string, rather than first add too many of them and afterwards remove the wrongly placed?
foreach($myArray as $key => &$value) {
$value = "'" . $value;
}
or (may be more readable as not by-reference)
foreach($myArray as $key => $value) {
$myArray[$key] = "'" . $value;
}
You can use rtrim - http://uk1.php.net/manual/en/function.rtrim.php to achieve. The generic syntax is:
<?php
$foo = 'my string\'';
$bar = rtrim($foo, '\'');
var_dump($foo); //shows my string'
var_dump($bar); //shows my string
so in your case take the array values, then use rtrim($myArray['myKey'], '\'') - this should do it for you :)
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 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
Is there a function that works like $_GET ?
I mean a function that transforms
"?var1=5&var2=true"
to
$var1=5;
$var2="true";
So that I can use one variable (string) in a function and fetch many variables from it?
Like:
function manual_GET($args){ /* ? */}
function myFunction($args)
{
manual_GET($args);
if(isset($var1))/* doesn't have to be this way, btw */
{
do_something($var1);
}
//etc
}
p.s. : I don't want to use $_GET with URL because this file is a class file (namely database_library.php) so I don't execute it directly, or make an AJAX call. I just require_once(); it.
Yes, there is. It is called parse_str: http://php.net/manual/en/function.parse-str.php
One way to fix it.
function myFunction($args){
return parse_str($args,$values);
}
function parseQueryString($str) {
$op = array();
$pairs = explode("&", $str);
foreach ($pairs as $pair) {
list($k, $v) = array_map("urldecode", explode("=", $pair));
$op[$k] = $v;
}
return $op;
}
it works like parse_str but doesn't convert spaces and dots to underscores
"?var1=5&var2=true"
foreach ($_GET AS $k=>$v){
$$k=$v;
}
echo $var1; // print 5
echo $var2; // print true