I have this problem:
One string like:
$stringa = "array('name' => 'John')"
I want obtain : array('name' => 'John') for use in my code like array
Any helps? Thanks
Caution using eval...
Caution The eval() language construct is very dangerous because it
allows execution of arbitrary PHP code. Its use thus is discouraged.
If you have carefully verified that there is no other option than to
use this construct, pay special attention not to pass any user
provided data into it without properly validating it beforehand.
<?php
$stringa = "array('name' => 'John')";
$code = "\$a = " . $stringa . ";";
eval($code);
print_r($a);
Gouda Elalfy was on the right idea, but his solution simply made the whole string a single array value.
First, we need to remove the excess datatype information:
$slimString = substr($stringa,6);
$slimString = rtrim($slimString,")");
This now gives us a string of:
'name' => 'John'
So then the Keys and the values in the string need to be split up,
so break at => as so:
For multiple values in the string:
This method also includes the single quotes to limit catching punctuation commas (please note this method was screwed up by trim not being as effective as I'd have liked and requiring str_replace quotes instead).
$slimString = str_replace("', '","=>", $slimString);
Then
$slimStringParts = explode("=>", $slimString);
This will split on => (or ,) so that multiple values of array contents can be generated.
Then cycle through each of the array pieces, on the basis that the EVEN numbers (and zero) are the Keys and the ODD numbers are the values, also removing the quotes as well for each one,
I was originally using trim but for some reason trim was not working as fully as I expected. so instead reverted to st_replace
foreach($slimStringParts as $key => $part){
if(($key%2) == 0){
$part = str_replace("'","",$part);
$arrayOutput[$part] = str_replace("'","",$slimStringParts[$key+1]);
}
}
unset($key, $part);
The foreach only acts upon the even and zero values as referenced above, and they take the original key value + 1 as their contents.
The trim/str_replace removes the single quotes and looks untidy but this works for a string of one or more array values
And finally the Output:
print_r($arrayOutput);
Test with the original:
input : "array('name' => 'John')"
Output : Array ( [name ] => John )
Tested with a multivalue array string:
input : "array('name' => 'John', 'surname' => 'James', 'Ride' => 'horse')"
Output : Array ( [name ] => John [surname ] => James [Ride ] => horse )
Full code:
$stringa = "array('name' => 'John')";
$stringb = "array('name' => 'John', 'surname' => 'James', 'Ride' => 'horse')";
$slimString = substr($stringb,6);
$slimString = rtrim($slimString,")");
$slimString = str_replace("', '","=>", $slimString);
$slimStringParts = explode("=>", $slimString);
foreach($slimStringParts as $key => $part){
if(($key%2) == 0){
$part = str_replace("'","",$part);
$arrayOutput[$part] = str_replace("'","",$slimStringParts[$key+1]);
}
}
unset($key,$part);
print_r($arrayOutput);
exit;
Please note my trim() idea was what I wanted but that seems to be influenced by my page character encoding :-(
You can use eval() function.
But it's not recommanded.
http://php.net/manual/en/function.eval.php
Eval is unsafe, try to use it as temporary method and find a better solution.
Example :
$stringa="array('name' => 'John');";
$array = eval($stringa);
Related
I have a script which creates an array containing entries for a table that I'd like to encode as json to send to my app. Each entry is an associative array of k/v pairs of string=>string|int. The code to generate the full array is as follows:
$entries = [];
foreach($stats as $i => $stat){
$playerStats = new Player_Stats($stat);
$entry = [
'place' => $i,
'name' => $playerStats->name(),
'elo' => $playerStats->currentRating(),
'highest' => $playerStats->highRating(),
'masterPoints' => $playerStats->onlineMasterPoints(),
'winLose' => $playerStats->matchesWonLost(),
'winRate' => $playerStats->winPercent(),
'numEvents' => $playerStats->numEvents(),
'wins' => $playerStats->eventsWon(),
'placed' => $playerStats->eventsPlaced()
];
$entries[] = $entry;
}
$result = json_encode($entries);
When I do a count or vardump etc on entries, It clearly shows that its been properly filled with the correct data. json_encode() returns false however. Using json_last_error_msg(), I get the UTF-8 error in the title: Malformed UTF-8 characters, possibly incorrectly encoded. All of the other posts on this issue I could find involved characters from other languages. All of the content in this array is made of the english alphabet and numbers, all ascii characters let alone utf-8.
Am I just missing something trivial (I usually am) or should I be looking for or trying something else completely?
You could use the option to ignore these, JSON_INVALID_UTF8_IGNORE so your code would be json_encode($data, JSON_INVALID_UTF8_IGNORE);
This will ignore invalid UTF-8 as the name describes. You can see all options for json_encode here. https://www.php.net/manual/en/function.json-encode.php
Something like this could do the trick:
$result = json_encode(array_map(utf8_encode, $entries))
I have a string that I want to explode by commas but only if the comma is not nested inside some parentheses. This is a fairly common use case, and I have been reading through answered posts in this forum, but not really found what I am looking for.
So, in detail: the point is, i have a string (= SQL SELECT ... FROM statement), and I want to extract the elements from the list separated by comma encoded in this string (= the name of the columns that one wants to select from. However, these elements can contain brackets, and effectively be function calls. For example, in SQL one could do
SELECT TO_CHAR(min(shippings.shippingdate), 'YYYY-MM-DD') as shippingdate, nameoftheguy FROM shippings WHERE ...
Obviously, I would like to have an array now containing as first element
TO_CHAR(min(shippings.shippingdate), 'YYYY-MM-DD') as shippingdate
and as second element
nameoftheguy
The approaches I have followed so far are
PHP and RegEx: Split a string by commas that are not inside brackets (and also nested brackets),
PHP: Split a string by comma(,) but ignoring anything inside square brackets?,
Explode string except where surrounded by parentheses?, and
PHP: split string on comma, but NOT when between braces or quotes?
(focussing on the regex expressions therein, since I would like to do it with a single regex line), but in my little test area, those do not give the proper result. In fact, all of them split nothing or too much:
$Input: SELECT first, second, to_char(my,big,house) as bigly, export(mastermind and others) as aloah FROM
$Output: Array ( [0] => first [1] => second [2] => to_char [3] => (my,big,house) [4] => as [5] => bigly [6] => export [7] => (mastermind and others) [8] => as [9] => aloah )
The code of my test area is
<?php
function test($sql){
$foo = preg_match("/SELECT(.*?)FROM/", $sql, $match);
$bar = preg_match_all("/(?:[^(|]|\([^)]*\))+/", $match[1], $list);
//$bar = preg_match_all("/\((?:[^()]|(?R))+\)|'[^']*'|[^(),\s]+/", $match[1], $list);
//$bar = preg_match_all("/[,]+(?![^\[]*\])/", $match[1], $list);
//$bar = preg_match_all("/(?:[^(|]|\([^)]*\))+/", $match[1], $list);
//$bar = preg_match_all("/[^(,\s]+|\([^)]+\)/", $match[1], $list);
//$bar = preg_match_all("/([(].*?[)])|(\w)+/", $match[1], $list);
print "<br/>";
return $list[0];
}
print_r(test("SELECT first, second, to_char(my,big,house) as bigly, export(mastermind and others) as aloah FROM"));
?>
As you can imagine, I am not an regex expert, but I would like to do this splitting in a single line, if it is possible.
Following the conversation here, I did write a parser to solve this problem. It is quite ugly, but it does the job (at least within some limitations). For completeness (if anybody else might run into the same question), I post it here:
function full($sqlu){
$sqlu = strtoupper($sqlu);
if(strpos($sqlu, "SELECT ")===false || strpos($sqlu, " FROM ")===false) return NULL;
$def = substr($sqlu, strpos($sqlu, "SELECT ")+7, strrpos($sqlu, " FROM ")-7);
$raw = explode(",", $def);
$elements = array();
$rem = array();
foreach($raw as $elm){
array_push($rem, $elm);
$txt = implode(",", $rem);
if(substr_count($txt, "(") - substr_count($txt, ")") == 0){
array_push($elements, $txt);
$rem = array();
}
}
return $elements;
}
When feeding it with the following string
SELECT first, second, to_char(my,(big, and, fancy),house) as bigly, (SELECT myVar,foo from z) as super, export(mastermind and others) as aloah FROM table
it returns
Array ( [0] => first [1] => second [2] => to_char(my,(big, and, fancy),house) as bigly [3] => (SELECT myVar,foo from z) as super [4] => export(mastermind and others) as aloah )
I have a bunch of variables I want to display of which some are empty. Some vars have spaces in them I want to preserve. I would like to display them as a comma delimited list. If I echo them sequentially var1, var2,.var6,.var10, I get extra commas where there are empties. Doesn't sound like it would be that hard to delete the extra commas, but my ideas have not worked.
Since I have many, many of these, I don't want to have to condition printing every one--allowing for first or last in placement of commas or iteratively replacing multiple commas with 1 comma or something complicated.. i.e. I'd like to find a simple repeatable approach that can be used whenever this comes up.
One idea was to convert the string into an array and delete empty values. I can strip out empty spaces and echoing, can print var1,var2,,,var8,,, with no problem. However, I can't find a way to delete the commas i.e., the empty values in array.
I tried:
$array = "one,two,,,six,,,ten";
$array= array_filter($array);
foreach($array as $val) {
echo $val;}}
foreach($array as $val) {
if ($val!=""&$val!=NULL) {
echo $val;}}
}
it doesn't get rid of commas. Have not had luck with following suggestions on web:
array_flip(array_flip($array); or
$array = array_values($array); or
Could be typo on my end, but would appreciate any suggestions from the experienced.
The reason you can not delete then is because you are not working with a valid array .. to work with a valid array you need to do this :
$array = "one,two,,,six,,,ten";
$array = explode(",",$array);
$array= array_filter($array);
var_dump($array);
Output
array
0 => string 'one' (length=3)
1 => string 'two' (length=3)
4 => string 'six' (length=3)
7 => string 'ten' (length=3)
To convert back to string use implode http://php.net/manual/en/function.implode.php
var_dump(implode(",", $array))
Output
string 'one,two,six,ten' (length=15)
Thanks
:)
I have array
[Company] => Demo Company 1
[First Name] => Test
[Last Name] => Lead 1
[Designation] => This is testing title 1
[Email] => email1#yopmail.com
[Phone] => 242377
I used extract() function so all the index values will become variable names, I also used {} as there are spaces in variable names. But i dont know why its not working :(
This ${'First Name'} returns blank...below is my code
foreach($vals as $value){
extract($value);
echo '<tr><td>'.${'First Name'}.' '.${"Last Name"}.'</td><td>'.$Company.'</td><td>'.$Phone.'</td><td>'.$Email.'</td></tr>';
}
Variable names cannot contain spaces. For reference, read the manual on variables:
A valid variable name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thus:
'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
If I were you, I'd just go with a shorter name on the array, so instead of $value use $v or similar. You can also use printf to make the code more readable:
foreach($vals as $v) {
printf('<tr><td>%s %s</td><td>%s</td><td>%s</td><t\
d>%s</td></tr>',
$LEADID,
$v['First Name'],
$v['Last Name'],
$v['Company'],
$v['Phone'],
$v['Email']);
}
I think you should remove the spaces before using extract:
$keys = str_replace( ' ', '', array_keys($vals));
$values = array_values($vals);
$vals = array_combine($keys, $values);
Then, after extract you'd have variables like $FirstName.
In this case you do not really need extract.
You can use array indexes in interpolated strings.
$sample = array('name' => 'frank, 'age' => 42);
echo "{$sample['name']} is {$sample['age']} years old.";
If you can avoid using ${'strange names'} you should do it. If yo REALLY need to do it this way:
Please update your question and tell us HOW $value is defined. Is vals The array from your first code block?
I am getting data from an API and the resulting string is
[RESPONSE]
PROPERTY[STATUS][0]=ACTIVE
PROPERTY[REGISTRATIONEXPIRATIONDATE][0]=2012-04-04 19:48:48
DESCRIPTION=Command completed successfully
QUEUETIME=0
CODE=200
RUNTIME=0.352
QUEUETIME=0
RUNTIME=0.8
EOF
I am trying to convert this into an array like
Array(
['PROPERTY[STATUS][0]'] => ACTIVE,
['CODE'] => 200,
...
);
So I am trying to explode it using the resulting file_get_content function with an explode like
$output = explode('=',file_get_contents($url));
But the problem is the returning values are not always returned in the same order, so I need to have it like $array['CODE'] = 200, and $array['RUNTIME'] = 0.352 however there does not seem to be any kind of new line characters? I tried \r\n, \n, <br>, \r\n\r\n in the explode function to no avail. But there is new lines in both notepad and the browser.
So my question is there some way to determine if a string is on a new line or determine what the character forcing the new line is? If not is there some other way I could read this into an array?
To find out what the breaking character is, you could do this (if $data contatins the string example you've posted):
echo ord($data[strlen('[RESPONSE]')]) . PHP_EOL;
echo ord($data[strlen('[RESPONSE]')+1]); // if there's a second char
Then take a look in the ASCII table to see what it is.
EDIT: Then you could explode the data using that newly found character:
explode(ord($ascii_value), $data);
Btw, does file() return a correct array?
Explode on "\n" with double quotes so PHP understands this is a line feed and not a backslashed n ;-) then explode each item on =
Why not just use parse_ini_file() or parse_ini_string()?
It should do everything you need (build an array) in one easy step.
Try
preg_split("/$/m", $str)
or
preg_split("/$\n?/m", $str)
for the split
The lazy solution would be:
$response = strtr($response, "\r", "\n");
preg_match_all('#^(.+)=(.+)\s*$#m', $response, $parts);
$parts = array_combine($parts[1], $parts[2]);
Gives you:
Array (
[PROPERTY[STATUS][0]] => ACTIVE
[PROPERTY[REGISTRATIONEXPIRATIONDATE][0]] => 2012-04-04 19:48:48
[DESCRIPTION] => Command completed successfully
[QUEUETIME] => 0
[CODE] => 200
[RUNTIME] => 0.8