Convert string to array value in PHP - php

If I had an array such as:
testarray = array('foo'=>34, 'bar'=>array(1, 2, 3));
How would I go about converting a string such as testarray[bar][0] to find the value its describing?

Well, you can do something like this (Not the prettiest, but far safer than eval)...:
$string = "testarray[bar][0]";
$variableBlock = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$regex = '/^('.$variableBlock.')((\[\w+\])*)$/';
if (preg_match($regex, $string, $match)) {
$variableName = $match[1]; // "testarray"
if (!isset($$variableName)) {
//Error, the variable does not exist
return null;
} else {
$array = $$variableName;
if (preg_match_all('/\[(\w+)\]/', $match[2], $matches)) {
foreach ($matches[1] as $match) {
if (!is_array($array)) {
$array = null;
break;
}
$array = isset($array[$match]) ? $array[$match] : null;
}
}
return $array;
}
} else {
//error, not in correct format
}

You could use PHP's eval function.
http://php.net/manual/en/function.eval.php
However, make absolutely sure the input is sanitized!
Cheers

Related

PHP Extracting Operators and the values from String

in my code i need to get both operator and the values to do my calculation. my code is,
$demension = "3.5x2.3=>4.8x8.9"
public function searchItems($dimension)
{
$out= preg_split('/[x-]/', $dimension);
$i=0;
foreach ($out as $key) {
preg_match('/(!=|=|<=|<|>=|>)/',$key,$matches);
if(!empty($matches))
{
$result[$i]=$matches;
}else
{
$result[$i]=$key;
}
$i++;
}
return $result;
}
I need to get 3.5,2.3,=>,4.8,8.9 separately
can any one show me the right path.
Here it is. Using a regexp to get values and operators.
function getParts($string)
{
$regexp = "/(\d+?\.\d+?)|([<>=]+)/";
$parts = [];
if (preg_match_all($regexp, $string, $matches)) {
$parts = $matches[0];
}
return $parts;
}
$dimension = "3.5x2.3=>4.8x8.9"
print_r(getParts($dimension));

How to check if a string inside of an array,contains a part of a string in php?

I have this code:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
if(in_array("backup", $arr)){
echo "Da";
} else { echo "Nu";
}
But is not working because,in_array instruction check the array for the complete string "backup" , which doesnt exist.I need to check for a part of the string,for example,to return true because backup is a part of the "Hello_backup" and "Beautiful_backup" strings
EDIT: I take the advice and i have used stripos like this:
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$word='backup';
if(stripos($arr,$word) !== false){
echo "Da";
} else { echo "Nu";}
but now i get an error: "stripos() expects parameter 1 to be string, array given in if(stripos($arr,$word) !== false){"
Use implode to basically concatenate the array values as a string, then use strpos to check for a string within a string.
The first argument you pass to implode is used to separate each value in the array.
$array = array("Hello_backup","World!","Beautiful_backup","Day!");
$r = implode(" ", $array);
if (strpos($r, "backup") !== false) {
echo "found";
}
In this case you need to use stripos(). Example:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$needle = 'backup';
function check($haystack, $needle) {
foreach($haystack as $word) {
if(stripos($word, $needle) !== false) {
return 'Da!'; // if found
}
}
return 'Nu'; // if not found
}
var_dump(check($arr, $needle));
Without a function:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$found = false;
foreach($arr as $word) {
if(stripos($word, 'backup') !== false) {
$found = true;
break;
}
}
if($found) {
echo 'Da!';
} else {
echo 'Nu';
}
Try with strpos()
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $v){
echo (strpos($v,"backup")!== false ? "Da" : "Nu");
}
output :- DaNuDaNu
Here is the one line solution for you.
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$returned_a = array_map(function($u){ if(stripos($u,'backup') !== false) return "Da"; else return "Nu";}, $arr);
You can use $returned_a with array as your answer..
Array ( [0] => Da [1] => Nu [2] => Da [3] => Nu )
Use this method. It is little bit simple to use.
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
print_r($matches);
Look this working example
According to your question
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
$matches = trim($matches);
if($matches != '')
{echo "Da";
}else { echo "Nu";}
<?php
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $arr1) {
if (strpos ($arr1,"backup")) {
echo "Da";
} else {
echo "Nu";
}
}
?>

extract values found in array from string

I am stuck. What I would like to do: In the $description string I would like to check if any of the values in the different arrays can be found. If any of the values match, I need to know which one per array. I am thinking that I need to do a function for each $a, $b and $c, but how, I don't know
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$a = array('1:100','1:250','1:10','2');
$a = getExtractedValue($a,$description);
$b = array('one','five','12');
$b = getExtractedValue($b,$description);
$c = array('6000','8000','500');
$c = getExtractedValue($c,$description);
}
}
}
function getExtractedValue($a,$description){
?
}
I would be very very greatful if anyone could help me with this.
many thanks Linda
It would be better to create each array just once and not in every iteration of the while loop.
Also using the same variable names in the loop is not recommended.
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
$a = array('1:100','1:250','1:10','2');
$b = array('one','five','12');
$c = array('6000','8000','500');
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$aMatch = getExtractedValue($a,$description);
$bMatch = getExtractedValue($b,$description);
$cMatch = getExtractedValue($c,$description);
}
}
}
Use strpos to find if the string exists (or stripos for case insensitive searches). See http://php.net/strpos. If the string exists it will return the matching value in the array:
function getExtractedValue($a,$description) {
foreach($a as $value) {
if (strpos($description, $value) !== false) {
return $value;
}
}
return false;
}
there s a php function for that which return a boolean.
or if you wanna check if one of the element in arrays is present in description, maybe you 'll need to iterate on them
foreach($array as element){
if(preg_match("#".$element."#", $description){
echo "found";
}
}
If your question is correctly phrased and indeed you are searching a string, you should try something like this:
function getExtractedValue($a, $description) {
$results = array();
foreach($a as $array_item) {
if (strpos($array_item, $description) !== FALSE) {
$results[] = $array_item;
}
}
return $results;
}
The function will return an array of the matched phrases from the string.
Try This..
if ( in_array ( $str , $array ) ) {
echo 'It exists'; } else {
echo 'Does not exist'; }

Retrieve $_POST variable from array name

Consider the following:
<input type="hidden" name="random[variable][here]" value="valueofrandom"/>
Is there a better way to retrieve its value if we have the name as a string? The following works, but it doesn't seem very smart.
function getPostValueFromName($name) {
// Example string name: random[variable][here]
$parts = preg_split('/\[|\]/i', $name, -1, PREG_SPLIT_NO_EMPTY);
if (isset($parts[3])) {
return $_POST[$parts[0]][$parts[1]][$parts[2][$parts[3]]];
} elseif (isset($parts[2])) {
return $_POST[$parts[0]][$parts[1]][$parts[2]];
} elseif (isset($parts[1])) {
return $_POST[$parts[0]][$parts[1]];
} else {
return $_POST[$parts[0]];
}
}
Thanks!
I use https://github.com/symfony/PropertyAccess for things like this.
Using it, you can get random[variable][here] with
$accessor = new PropertyAccessor();
$val = $accessor->getValue($_POST, 'random.variable.here');
// or
$val = $accessor->getValue($_POST, 'random[variable][here]');

Convert a String to Variable

I've got a multidimensional associative array which includes an elements like
$data["status"]
$data["response"]["url"]
$data["entry"]["0"]["text"]
I've got a strings like:
$string = 'data["status"]';
$string = 'data["response"]["url"]';
$string = 'data["entry"]["0"]["text"]';
How can I convert the strings into a variable to access the proper array element? This method will need to work across any array at any of the dimensions.
PHP's variable variables will help you out here. You can use them by prefixing the variable with another dollar sign:
$foo = "Hello, world!";
$bar = "foo";
echo $$bar; // outputs "Hello, world!"
Quick and dirty:
echo eval('return $'. $string . ';');
Of course the input string would need to be be sanitized first.
If you don't like quick and dirty... then this will work too and it doesn't require eval which makes even me cringe.
It does, however, make assumptions about the string format:
<?php
$data['response'] = array(
'url' => 'http://www.testing.com'
);
function extract_data($string) {
global $data;
$found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
if (!$found_matches) {
return null;
}
$current_data = $data;
foreach ($matches[1] as $name) {
if (key_exists($name, $current_data)) {
$current_data = $current_data[$name];
} else {
return null;
}
}
return $current_data;
}
echo extract_data('data["response"]["url"]');
?>
This can be done in a much simpler way. All you have to do is think about what function PHP provides that creates variables.
$string = 'myvariable';
extract(array($string => $string));
echo $myvariable;
done!
You can also use curly braces (complex variable notation) to do some tricks:
$h = 'Happy';
$n = 'New';
$y = 'Year';
$wish = ${$h.$n.$y};
echo $wish;
Found this on the Variable variables page:
function VariableArray($data, $string) {
preg_match_all('/\[([^\]]*)\]/', $string, $arr_matches, PREG_PATTERN_ORDER);
$return = $arr;
foreach($arr_matches[1] as $dimension) { $return = $return[$dimension]; }
return $return;
}
I was struggling with that as well,
I had this :
$user = array('a'=>'alber', 'b'=>'brad'...);
$array_name = 'user';
and I was wondering how to get into albert.
at first I tried
$value_for_a = $$array_name['a']; // this dosen't work
then
eval('return $'.$array_name['a'].';'); // this dosen't work, maybe the hoster block eval which is very common
then finally I tried the stupid thing:
$array_temp=$$array_name;
$value_for_a = $array_temp['a'];
and this just worked Perfect!
wisdom, do it simple do it stupid.
I hope this answers your question
You would access them like:
print $$string;
You can pass by reference with the operator &. So in your example you'll have something like this
$string = &$data["status"];
$string = &$data["response"]["url"];
$string = &$data["entry"]["0"]["text"];
Otherwise you need to do something like this:
$titular = array();
for ($r = 1; $r < $rooms + 1; $r ++)
{
$title = "titular_title_$r";
$firstName = "titular_firstName_$r";
$lastName = "titular_lastName_$r";
$phone = "titular_phone_$r";
$email = "titular_email_$r";
$bedType = "bedType_$r";
$smoker = "smoker_$r";
$titular[] = array(
"title" => $$title,
"first_name" => $$firstName,
"last_name" => $$lastName,
"phone" => $$phone,
"email" => $$email,
"bedType" => $$bedType,
"smoker" => $$smoker
);
}
There are native PHP function for this:
use http://php.net/manual/ru/function.parse-str.php (parse_str()).
don't forget to clean up the string from '"' before parsing.
Perhaps this option is also suitable:
$data["entry"]["0"]["text"];
$string = 'data["entry"]["0"]["text"]';
function getIn($arr, $params)
{
if(!is_array($arr)) {
return null;
}
if (array_key_exists($params[0], $arr) && count($params) > 1) {
$bf = $params[0];
array_shift($params);
return getIn($arr[$bf], $params);
} elseif (array_key_exists($params[0], $arr) && count($params) == 1) {
return $arr[$params[0]];
} else {
return null;
}
}
preg_match_all('/(?:(\w{1,}|\d))/', $string, $arr_matches, PREG_PATTERN_ORDER);
array_shift($arr_matches[0]);
print_r(getIn($data, $arr_matches[0]));
P.s. it's work for me.

Categories