I have following array
$type=Array(
[0] => PL
[1] => LWP
[2] => Carry Forward
[3] => SL
);
I want to convert it into String.I used implode function to convert it.
$newarray=implode(",", $type);
but it reurn string like below
PL,LWP,Carry Forward,SL
I want String like below
("PL","LWP","Carry Forward","SL")
Please help me...
Try this one ;)
$newarray='("'.implode('","', $type).'")';
As you want double quotes in the string generated,you can replace the glue of implode with implode('", "', $type) instead of implode(", ", $type)
These double quotes will not appear in the 1st and last value of string.. So add (" in the beginning and ") at the end of implode.
See the code below for entire syntax
<?php
$type=Array(
[0] => PL
[1] => LWP
[2] => Carry Forward
[3] => SL
);
//Convert array to string with double quotes for each value
$newarray='("'.implode('", "', $type).'")';
echo $newarray;
?>
You can try with "," glue and adding prefix (" and postfix ")
$newarray= '("' . implode('","', $type) . '")';
You should also think about edge case when you have empty array since you may want to handle it slightly different. In this case it would result ("")
As it stands, your question is unanswerable. You are trying to create a machine parseable representation of data without providing nearly enough information about how this is to be parsed.
e.g. What if one the elements already contains a double quote - you need to escape it. But which method do you use for escaping?
e.g. Quoting a numerical value may then affect its interpretation by the consumer of the data (although your example does not include numerical data).
You might consider using fputcsv(); (but this will only write to a stream - so if you need the data elsewhere then you'd need to capture the stream.
The current answers disregard the edge case of $type being empty by returning ("") instead of () which is probably what you want.
You may want to surround each element by quotes before adding the parentheses like so:
$type = array("PL", "LWP", "Carry Forward", "SL");
$quoted = array_map( function($element) { return "\"${element}\""; }, $type );
$newarray = '(' . implode(',', $quoted) . ')';
Related
Background..
This is user input being collected so I need to expect some strange stuff and try to fix up string before passing these into functions. User input is stored into the database similar to so:
{"value":"O'Neil,'Smith',\"O'Reilly\",100"}
So the script pulls these out of the database, json_decodes them, and then now I'm trying to fix those value strings up. Here's the best example of that I can give.
$json = '{"value":"O\'Neil,\'Smith\',\"O\'Reilly\",100"}';
$array = json_decode($json, true);
The Goal..
How could I go about escaping quotes in strings like so:
O'Neil,Smith,O'Reilly,100
"O'Neil","Smith","O'Reilly",100
'O'Neil','Smith','O'Reilly',100
O'Neil,'Smith',"O'Reilly",100
So that I get the following result out of each:
'O\'Neil','Smith','O\'Reilly',100
Values may or may not contain commas. It could just be a single value like O'Neil or 100.
I'm pretty sure preg_replace could so something like this, or even preg_replace_callback, but I'm just not sure how to go about this.
The below do not work at all but I'm thinking one of these approaches should work.
$value = preg_replace('/(.*?)/', '$1', $array['value']);
$value = preg_replace_callback('/(.*?)/', 'addslashes', $array['value']);
I've also tried exploding the strings using the commas and looping the values but that escapes the quotes I don't want to touch as well.
Thanks all!
I think this function will do what you want. It uses preg_match_all to find either a quoted string (single or double, possibly with escaped quotes inside), or a set of non-comma characters. Each of those values is then trimmed of quotes, and any non-escaped single quotes are replaced with escaped ones. Finally non-numeric values are placed into single quotes:
function quote($value) {
preg_match_all('/"(?:\\\\"|[^"])*"|\'(?:\\\\\'|[^\'])*\'|[^,]+/', $value, $values);
foreach ($values[0] as &$value) {
$value = trim($value, "'\"");
$value = preg_replace("/(?<!\\\\)'/", "\\'", $value);
if (!is_numeric($value)) $value = "'$value'";
}
return implode(',', $values[0]);
}
To use with your sample strings:
echo quote("O'Neil,Smith,O'Reilly,100") . PHP_EOL;
echo quote("\"O'Neil\",\"Smith\",\"O'Reilly\",100") . PHP_EOL;
echo quote("'O\'Neil','Smith','O\'Reilly',100") . PHP_EOL;
echo quote("O'Neil,'Smith',\"O'Reilly\",100") . PHP_EOL;
Output:
'O\'Neil','Smith','O\'Reilly',100
'O\'Neil','Smith','O\'Reilly',100
'O\'Neil','Smith','O\'Reilly',100
'O\'Neil','Smith','O\'Reilly',100
Demo on 3v4l.org
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);
I am getting an error when trying to unserialize data. The following error occurs:
unserialize(): Error at offset 46 of 151 bytes
Here is the serialized data:
s:151:"a:1:{i:0;a:4:{s:4:"name";s:15:"Chloe O'Gorman";s:6:"gender";s:6:"female";s:3:"age";s:3:"3_6";s:7:"present";s:34:"Something from Frozen or a jigsaw ";}}";
The error is being caused by a single quote in the data. How can I alleviate this problem when the site and database that I am working with is already live?
Unfortunately I cannot rewrite the code that was responsible for serializing and inserting the data to the database. It is highly likely that there are multiple occurrences of this problem across the database.
Is there a function I can use to escape the data?
After doing further research I have found a work around solution. According to this blog post:
"It turns out that if there's a ", ', :, or ; in any of the array
values the serialization gets corrupted."
If I was working on a site that hadn't yet been put live, a prevention method would have been to base64_encode my serialized data before it was stored in the database like so:
base64_encode( serialize( $my_data ) );
And then:
unserialize( base64_decode( $encoded_serialized_string ) );
when retrieving the data.
However, as I cannot change what has already been stored in the database, this very helpful post(original post no longer available, but looks like this) provides a solution that works around the problem:
$fixed_serialized_data = preg_replace_callback ( '!s:(\d+):"(.*?)";!', function($match) {
return ($match[1] == strlen($match[2])) ? $match[0] : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
}, $my_data );
$result = unserialize( $fixed_serialized_data );
From what I see, you have a valid serialized string nested inside of a valid serialized string -- meaning serialize() was called twice in the formation of your posted string.
See how you have s:151: followed by:
"a:1:{i:0;a:4:{s:4:"name";s:15:"Chloe O'Gorman";s:6:"gender";s:6:"female";s:3:"age";s:3:"3_6";s:7:"present";s:34:"Something from Frozen or a jigsaw ";}}";
тод that is a valid single string that contains pre-serialized data.
After you unserialize THAT, you get:
a:1:{i:0;a:4:{s:4:"name";s:15:"Chloe O'Gorman";s:6:"gender";s:6:"female";s:3:"age";s:3:"3_6";s:7:"present";s:34:"Something from Frozen or a jigsaw ";}}
// ^^--^^^^^^^^^^^^^^-- uh oh, that string value has 14 bytes/characters not 15
It looks like somewhere in the string processing, and escaping slash was removed and that corrupted the string.
There is nothing foul about single quotes in serialized data.
You can choose to either:
execute an escaping call to blindly apply slashes to ALL single quotes in your string (which may cause breakages elsewhere) -- assuming you WANT to escape the single quotes for your project's subsequent processes or
execute my following snippet which will not escape the single quotes, but rather adjust the byte/character count to form a valid
Code: (Demo)
$corrupted_byte_counts = <<<STRING
s:151:"a:1:{i:0;a:4:{s:4:"name";s:15:"Chloe O'Gorman";s:6:"gender";s:6:"female";s:3:"age";s:3:"3_6";s:7:"present";s:34:"Something from Frozen or a jigsaw ";}}";
STRING;
$repaired = preg_replace_callback(
'/s:\d+:"(.*?)";/s',
function ($m) {
return 's:' . strlen($m[1]) . ":\"{$m[1]}\";";
},
unserialize($corrupted_byte_counts) // first unserialize string before repairing
);
echo "corrupted serialized array:\n$corrupted_byte_counts";
echo "\n---\n";
echo "repaired serialized array:\n$repaired";
echo "\n---\n";
print_r(unserialize($repaired)); // unserialize repaired string
echo "\n---\n";
echo serialize($repaired);
Output:
corrupted serialized array:
s:151:"a:1:{i:0;a:4:{s:4:"name";s:15:"Chloe O'Gorman";s:6:"gender";s:6:"female";s:3:"age";s:3:"3_6";s:7:"present";s:34:"Something from Frozen or a jigsaw ";}}";
---
repaired serialized array:
a:1:{i:0;a:4:{s:4:"name";s:14:"Chloe O'Gorman";s:6:"gender";s:6:"female";s:3:"age";s:3:"3_6";s:7:"present";s:34:"Something from Frozen or a jigsaw ";}}
---
Array
(
[0] => Array
(
[name] => Chloe O'Gorman
[gender] => female
[age] => 3_6
[present] => Something from Frozen or a jigsaw
)
)
---
s:151:"a:1:{i:0;a:4:{s:4:"name";s:14:"Chloe O'Gorman";s:6:"gender";s:6:"female";s:3:"age";s:3:"3_6";s:7:"present";s:34:"Something from Frozen or a jigsaw ";}}";
*keep in mind, if you want to return your data to its original Matryoshka-serialized form, you will need to call serialize() again on $repaired.
**if you have substrings that contain "; in them, you might try this extended version of my snippet.
There's nothing wrong with your serialized text as posted. The quotes inside do NOT need to be escaped, because PHP uses the type length indicators to figure out where things start/stop. e.g.
php > $foo = "This string contains a \" quote and a ' quote";
php > $bar = serialize($foo);
php > $baz = unserialize($bar);
php > echo "$foo\n$bar\n$baz\n";
This string contains a " quote and a ' quote
s:44:"This string contains a " quote and a ' quote";
This string contains a " quote and a ' quote
Note the lack of ANY kind of escaping in the serialized string - the quotes inside the string are there as-is, no quoting, no escaping, no encoding.
As posted, your serialized data properly deserializes into a plain JSON string without issue.
php nowdoc
unserialize(<<<'DDDD'
[SERIALIZE_STR]
DDDD
);
I have strings like these:
"my value1" => my value1
"my Value2" => my Value2
myvalue3 => myvalue3
I need to get rid of " (double-quotes) in end and start, if these exist, but if there is this kind of character inside String then it should be left there. Example:
"my " value1" => my " value1
How can I do this in PHP - is there function for this or do I have to code it myself?
The literal answer would be
trim($string,'"'); // double quotes
trim($string,'\'"'); // any combination of ' and "
It will remove all leading and trailing quotes from a string.
If you need to remove strictly the first and the last quote in case they exist, then it could be a regular expression like this
preg_replace('~^"?(.*?)"?$~', '$1', $string); // double quotes
preg_replace('~^[\'"]?(.*?)[\'"]?$~', '$1', $string); // either ' or " whichever is found
If you need to remove only in case the leading and trailing quote are strictly paired, then use the function from Steve Chambers' answer
However, if your goal is to read a value from a CSV file, fgetcsv is the only correct option. It will take care of all the edge cases, stripping the value enclosures as well.
I had a similar need and wrote a function that will remove leading and trailing single or double quotes from a string:
/**
* Remove the first and last quote from a quoted string of text
*
* #param mixed $text
*/
function stripQuotes($text) {
return preg_replace('/^(\'(.*)\'|"(.*)")$/', '$2$3', $text);
}
This will produce the outputs listed below:
Input text Output text
--------------------------------
No quotes => No quotes
"Double quoted" => Double quoted
'Single quoted' => Single quoted
"One of each' => "One of each'
"Multi""quotes" => Multi""quotes
'"'"#";'"*&^*'' => "'"#";'"*&^*'
Regex demo (showing what is being matched/captured): https://regex101.com/r/3otW7H/1
trim will remove all instances of the char from the start and end if it matches the pattern you provide, so:
$myValue => '"Hi"""""';
$myValue=trim($myValue, '"');
Will become:
$myValue => 'Hi'.
Here's a way to only remove the first and last char if they match:
$output=stripslashes(trim($myValue));
// if the first char is a " then remove it
if(strpos($output,'"')===0)$output=substr($output,1,(strlen($output)-1));
// if the last char is a " then remove it
if(strripos($output,'"')===(strlen($output)-1))$output=substr($output,0,-1);
As much as this thread should have been killed long ago, I couldn't help but respond with what I would call the simplest answer of all. I noticed this thread re-emerging on the 17th so I don't feel quite as bad about this. :)
Using samples as provided by Steve Chambers;
echo preg_replace('/(^[\"\']|[\"\']$)/', '', $input);
Output below;
Input text Output text
--------------------------------
No quotes => No quotes
"Double quoted" => Double quoted
'Single quoted' => Single quoted
"One of each' => One of each
"Multi""quotes" => Multi""quotes
'"'"#";'"*&^*'' => "'"#";'"*&^*'
This only ever removes the first and last quote, it doesn't repeat to remove extra content and doesn't care about matching ends.
This is an old post, but just to cater for multibyte strings, there are at least two possible routes one can follow. I am assuming that the quote stripping is being done because the quote is being considered like a program / INI variable and thus is EITHER "something" or 'somethingelse' but NOT "mixed quotes'. Also, ANYTHING between the matched quotes is to be retained intact.
Route 1 - using a Regex
function sq_re($i) {
return preg_replace( '#^(\'|")(.*)\1$#isu', '$2', $i );
}
This uses \1 to match the same type quote that matched at the beginning. the u modifier, makes it UTF8 capable (okay, not fully multibyte supporting)
Route 2 - using mb_* functions
function sq($i) {
$f = mb_substr($i, 0, 1);
$l = mb_substr($i, -1);
if (($f == $l) && (($f == '"') || ($f == '\'')) ) $i = mb_substr($i, 1, mb_strlen( $i ) - 2);
return $i;
}
You need to use regular expressions, look at:-
http://php.net/manual/en/function.preg-replace.php
Or you could, in this instance, use substr to check if the first and then the last character of the string is a quote mark, if it is, truncate the string.
http://php.net/manual/en/function.substr.php
How about regex
//$singleQuotedString="'Hello this 'someword' and \"somewrod\" stas's SO";
//$singleQuotedString="Hello this 'someword' and \"somewrod\" stas's SO'";
$singleQuotedString="'Hello this 'someword' and \"somewrod\" stas's SO'";
$quotesFreeString=preg_replace('/^\'?(.*?(?=\'?$))\'?$/','$1' ,$singleQuotedString);
Output
Hello this 'someword' and "somewrod" stas's SO
If you like performance over clarity this is the way:
// Remove double quotes at beginning and/or end of output
$len=strlen($output);
if($output[0]==='"') $iniidx=1; else $iniidx=0;
if($output[$len-1]==='"') $endidx=-1; else $endidx=$len-1;
if($iniidx==1 || $endidx==-1) $output=substr($output,$iniidx,$endidx);
The comment helps with clarity...
brackets in an array-like usage on strings is possible and demands less processing effort than equivalent methods, too bad there isnt a length variable or a last char index
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