Parse variables in PHP string - php

NOTE: Eval is used here in total knowledge, the string parsed is entered by an administrator only, and the purpose is to store instructions in database, without restrictions to the instructions.
If you have a good alternative, it is always appreciated, but don't just say "eval is bad".
I have a String in PHP, for example
$myString = "(35*$var1*64)/$var2";
I want to eval() this string, but before, I want to modify all the variables in the string like this:
$var2 -> $_POST['var2']
There may or may not be a blank space after the variable in $myString .
When I eval $myString, PHP throws an error "Undefined variable $var1". PHP read the string and parse the variables, so I guess there should be a way to parse all the variables in the string.
The output should be:
$myStringParsed = "(35*$_POST['var1']*64)/$_POST['var2']";
or an equivalent.

Not maybe the best solution, but you can preprocess $_POST variable and generate $variablesString like this:
$variablesString = '';
foreach($_POST as $key => $val) {
$variablesString .= '$' . $key . ' = ' . $val . ';' . PHP_EOL;
}
eval($variablesString . PHP_EOL . $myString)
For string support you can check if $val is string, and if yes - wrap it with quotes.
Second way
$myString = 'return (35 * $var1 * 64) / $var2;';
$re = "/\\$(\\w*)/im";
preg_match_all($re, $myString, $matches);
foreach($matches[1] as $match) {
$search = '$' . $match;
$replace = '$_POST[\'' . $match . '\']';
$myString = str_replace($search, $replace, $myString);
}
echo eval($myString);
You can check it here

Assuming you mean....
$myString = '(35*$var1*64)/$var2';
The a more robust solution (consider $myvar10) than that suggested by ASGM is:
$replace=array(
'/\b\$var1\b/'=>$_POST['var1'],
'/\b\$var2\b/'=>$_POST['var2'],
...
);
$interpolated=preg_replace(array_keys($replace)
, $replace, $myString);
Note that I would recommend that you interpolate the string with literals rather than substituting one place holder for another. In addition to eliminating unnecessary processing, it also means you can check the content of the resulting string to ensure it only contains digits and operators (and a restricted number of functions if appropriate).

You are using wrong string enclosing quotes. Use '(35*$var1*64)/$var2':
//$var1 = $_POST['var1'];
//$var2 = $_POST['var2'];
$var1 = '10';
$var2 = '20';
$myString = 'return (35 * $var1 * 64) / $var2;';
echo eval($myString);
//1120
Working example of eval
If you want to take any variable from POST, than you can use extract() to get array keys as variables with associated values:
<?php
// Change it to real $_POST
$POST = [
'var1' => '10',
'var2' => '20',
];
extract($POST, EXTR_SKIP);
$myString = 'return (35 * $var1 * 64) / $var2;';
echo eval($myString);

Related

Adding something to the start of a variable?

I am looking for some code that allows you to add +44 onto the beginning of my $string variable.
So the ending product would be:
$string = 071111111111
+44071111111111
Your $string variable isn't actually a string in this scenario; it's an integer. Make it a string by putting quotes around it:
$string = "071111111111"
Then you can use the . operator to append one string to another, so you could do this:
$string = "+44" . $string
Now $string is +44071111111111. You can read more about how to use the . (string concatenation operator) on the PHP documentation here.
Other people's suggestions of just keeping $string as an integer wouldn't work: "+44" . 071111111111 is actually +447669584457. Due to the 0 at the start of the number, PHP converts it to an octal number rather than a decimal one.
You can combine strings by .
$string = '+44'.$string;
You can use universal code, which works with another parameters too.
<?php
$code = "+44";
$string = "071111111111";
function prepend(& $string, $code) {
$test = substr_replace($string, $code, 0, 0);
echo $test;
}
prepend($string, $code);
?>

Check if URL contains string then create variables with url strings

I need to check if URL contains the term: "cidades".
For example:
http://localhost/site/cidades/sp/sorocaba
So, if positive, then I need to create two or three variables with the remaining content without the " / ", in this case:
$var1 = "sp";
$var2 = "sorocaba";
These variables will be cookies values in the beggining of the page, then, some sections will use as wp-query these values to filter.
This should work for you:
Here I check with preg_match() if the search word is in the url $str between two slashes. If yes I get the substr() from the url after the search word and explode() it into an array with a slash as delimiter. Then you can simply loop through the array an create the variables with complex (curly) syntax.
<?php
$str = "http://localhost/site/cidades/sp/sorocaba";
$search = "cidades";
if(preg_match("~/$search/~", $str, $m, PREG_OFFSET_CAPTURE)) {
$arr = explode("/", substr($str, $m[0][1]+strlen($m[0][0])));
foreach($arr as $k => $v)
${"var" . ($k+1)} = $v;
}
echo $var1 . "<br>";
echo $var2;
?>
output:
sp
sorocaba
Here are two functions that will do it for you:
function afterLast($haystack, $needle) {
return substr($haystack, strrpos($haystack, $needle)+strlen($needle));
}
And PHP's native explode.
First call afterLast, passing the /cidades/ string (or just cidades if you don't expect the slashes). Then take the result and explode on / to get your resulting array.
It would look like:
$remaining_string = afterLast('/cidades/', $url);
$items = explode('/', $remaining_string)
Just note that if you do not include the / marks with the afterLast call, your first element in the explode array will be empty.
I think this solution is better, since the resulting array will support any number of values, not just two.

Add double quote between text seperated by comma [duplicate]

This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";

Is there a way to "cut" and "paste" parts of a string in PHP

I want to remove the first character of a string like so,
$a1 = "A10";
$a2 = substr($a1,1,strlen($startsem1)-1);
but I want to retrieve that removed "A" later on. Is there a way I can "cut" or "copy" that removed "A" to some variable?
Use substr again.
$a3 = substr($a1, 0, 1);
or as others commented, just split the string on whatever delimiter you're interested in using.
You can do directly this way:-
<?php
$result1 = "A10";
$result2 = $result1{0};
echo "$result1{0} : " . $result1{0} . "\n";
echo "$result2 : " . $result2 . "\n";
?>
Result:
A10{0} : A
A : A
Refer LIVE DEMO
Did you mean:
$a1 = "A10";
$a2 = substr($a1,1,strlen($a1)-1);
echo $a1[0]; // output "A" eg old value for you
echo $a2; // output "10"
PHP supports array like syntax for strings too so $a1[0] (zero based index as in array) extracts first letter from string.
For fun, you could do this:
$a1 = "A10";
$split = str_split( $a1); // Split the string into an array
$first_char = array_shift( $split);
$everything_else = implode( '', $split);
You can save it in its own variable (here I use string indexing to get the first character, but you may just as well use substr):
$saved_a = $a1[0];
Also note that you may skip the third parameter to substr if you want to get the rest of the string:
$a2 = substr($a1, 1);

PHP: concatenation of multidimensional array elements

I want to concatenate one element of a multidimensional array with some strings.
<?
$string1 = 'dog';
$string2 = array
(
'farm' => array('big'=>'cow', 'small'=>'duck'),
'jungle' => array('big'=>'bear', 'small'=>'fox')
);
$string3 = 'cat';
$type = 'farm';
$size = 'big';
$string = "$string1 $string2[$type][$size] $string3";
echo($string);
?>
By using this syntax for $string, I get:
dog Array[big] cat
I would like not to use the alternate syntax
$string = $string1 . ' ' . $string2[$type][$size] . ' ' . $string3;
which works.
What's wrong with "$string1 $string2[$type][$size] $string3"?
Use the "complex syntax":
$string = "$string1 {$string2[$type][$size]} $string3";
PHP's variable parsing is quite simple. It will recognize one level array access, but not more level. By enclosing the expression in {} you explicitly state which part of the string is a variable.
See PHP - Variable parsing.
I'm not a fan of complex syntax, or variable parsing in strings. Normally I would use the "alternate" syntax you described. You could do this as well:
$string = implode(' ', array($string1, $string2[$type][$size], $string3));
Use this:
$string = "$string1 {$string2[$type][$size]} $string3";

Categories