I am trying to parse following string...
IN.Tags.Share({"count":180,"url":"http://domain.org"}
is my following approach correct to get the value of count?
$str = 'IN.Tags.Share({"count":180,"url":"http://domain.org"}';
$data = explode(':', $str);
$val = explode(',', $data[1]);
return $val[0];
Or is there any better way to handling this type of strings? I think it could be done using regex as well.
thanks.
If course I'm not sure if your format will be constant, but part of your string looks like JSON. If always like this, you could do:
$str = str_replace('IN.Tags.Share(', '', $str);
$values = json_decode($str);
echo $values->count;
I would suggest pulling out the JSON by applying this regex to the string: IN\.Tags\.Share\((.*)\. Pull out the first group, and use json_decode: http://php.net/manual/en/function.json-decode.php
That way, you can directly access the data. It will support complex data structures as well.
Related
I have this Json Object Below, I want to extract this data and output it in PHP
{"seat_booked":"A5","0":"A5","1":"A3"}
then get them into this format
$seat_booked = "'A5', 'A5', 'A3'";
How can I do this?
I hope you are looking for this, its very simple example by using json_decode():
$string = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = json_decode($string,true);
$resuiredString = '"'."'".implode("','", $decoded)."'".'"';
echo $resuiredString;
Result:
"'A5','A5','A3'"
Side Note:
I suggest you to learn about variable concatenation.
PHP Concatenation
Another solution:
$json = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = array_map(
function($val) {
return "'". $val."'";
},
array_values(json_decode($json, true))
);
To get an object from a json in php you can use json_decode has explained here.
But you have another problem, your json is wrong!
If you want to represent a single dimensional array you should at least do this
["A5","A5","A3"]
Finally, using json_decode:
$obj = json_decode('["A5","A5","A3"]');
var_dump($obj);
Also, you could do something like:
{"0":"A5","1":"A5","2":"A3"}
$obj = json_decode('{"0":"A5","1":"A3", "2": "A5"}', true);
var_dump($obj);
Edit:
It's not very clear from your question if you are trying to get back an object from a json or if you just want to get a string from it.
If what you need is an string then you don't even need json, you could do this by string manipulation and/or using regex.
But just for completeness, if a quoted comma separated string is what you need you can do this:
$array = json_decode('["A5","A5","A3"]');
$str = implode("','",$array);
$str = "'" . $str . "'";
var_dump($str);
i got a piece of code that so far returns me data like this when i use print $result;
ssl_card_number=41**********1111
ssl_exp_date=0213
ssl_amount=132.86
ssl_salestax=0.00
ssl_invoice_number=5351353519500
ssl_result=0
ssl_result_message=APPROVED
ssl_txn_id=00000000-0000-0000-0000-00000000000
ssl_approval_code=123456
ssl_cvv2_response=P
ssl_avs_response=X
ssl_account_balance=0.00
ssl_txn_time=11/21/2012 12:38:20 PM
thats from view page source.
and the page itself shows it as :
ssl_card_number=41**********1111 ssl_exp_date=0213 ssl_amount=132.86 ssl_salestax=0.00 ssl_invoice_number=8601353519473 ssl_result=0 ssl_result_message=APPROVED ssl_txn_id=00000000-0000-0000-0000-00000000000 ssl_approval_code=123456 ssl_cvv2_response=P ssl_avs_response=X ssl_account_balance=0.00 ssl_txn_time=11/21/2012 12:37:54 PM
i need to be able to handle each of the "keys" in a better way and dont know how to explode them maybe ?
One possible approach:
parse_str(preg_replace('#\s+(?=\w+=)#', '&', $result), $array);
var_dump($array);
Explanation: preg_replace will turn all the whitespace before the param names into '&' symbol - making this string similar to the regular GET request url. Then parse_str (the function created specifically for parsing such urls) will, well, parse this string (sent as the first param), making an associative array of it.
In fact, you don't even have to use preg_replace here, if each param=value string begins from a new line; str_replace("\n", '&') should do the trick.
An alternative approach:
$pairs = preg_split('#\s+(?=\w+=)#', $x);
foreach ($pairs as $pair) {
list ($key, $value) = explode('=', $pair, 2);
$array[$key] = $value;
}
Here you first create an array of 'key-value pair' strings, then split each element by =: the first part would be the key, the second - the value.
You can use the regular expression reported by #raina77ow or you could use explodes (riskier):
<?php
$tmps = explode("\n",$result); //this gives you each line separate
foreach($tmps as $tmp){
list($key,$value) = explode('=',$tmp,2);
echo $key.' has value '.$value."\n";
//you can even create vars with the "key" if you are sure that they key is a "clean" string:
$$key=$value;
//or put everything into an array - similar to the regexp
$result_array[$key] = $value;
}
?>
Let say I've this URL:
http://example.com/image-title/987654/
I want to insert "download" to the part between "image-title" and "987654" so it would look like:
http://example.com/image-title/download/987654/
help would be greatly appreciated! thank you.
Assuming your URIs will always be the same (or at least predictable) format, you can use the explode function to split the URI into each of its parts, and then use array_splice to insert elements into that array, and finally use implode to put it all back together into a single string.
Note that you can insert elements into an array by specifying the $length parameter as zero. For example:
$myArray = array("the", "quick", "fox");
array_splice($myArray, 2, 0, "brown");
// $myArray now equals array("the", "quick", "brown", "fox");
There are a number of ways to do this in PHP:
Split and reconstruct using explode(), array_merge, implode()
Using substring()
Using a regular expression
Using str_replace
Assuming all the url's conform to the same structure (image-title/[image_id]) i recommend using str_replace like so:
$url = str_replace('image-title', 'image-title/download', $url);
If however image-title is dynamic (the actual title of the image) i recommend splitting and reconstructing like so:
$urlParts = explode('/', $url);
$urlParts = array_merge(array_slice($urlParts, 0, 3), (array)'download', array_slice($urlParts, 3));
$url = implode('/', $urlParts);
Not very well formatted, but i think this is what you need
$mystr= 'download';
$str = 'http://example.com/image-title/987654/';
$newstr = explode( "http://example.com/image-title",$str);
$constring = $mystr.$newstr[1];
$adding = 'http://example.com/image-title/';
echo $adding.$constring; // output-- http://example.com/image-title/download/987654/
I have this query:
list[One]=1&list[Two]=2&list[Apple]=fruit
this is the regex I use to return the values in the brackets and after the equal sign
preg_match_all('/(?<query>list\[(?<pagename>.*?)\]\=(?<parent>.*?))/',$source,$array);
returns:
One=
Two=
Apple=
Values that come after the equal sign are missing. Where's my mistake?
By the way, this query is generated with jquery's serialize(). Is there a better method to parse the values?
As I made in a comment, you may want to look in to parse_str
However, if you change the final .*? to something like [^&]* then you'll probbaly have better luck (assuming this is a GET query string (or some facsimile) as & will have to be escaped from the sequence with %26)
(?<parent>.*?) matches an empty string, so the result ist 'correct'. Try (?<parent>[^&]+) instead:
preg_match_all('/(?<query>list\[(?<pagename>.*?)\]\=(?<parent>[^&]+))/',$source,$array);
Because you use the non-greedy ? for <parent>, it's not grabbing the values. Try the other answers or if you can count on the format list[<name>]=<value> then you can avoid using regex altogether.
$query = 'list[One]=1&list[Two]=2&list[Apple]=fruit';
$pieces = explode('&', $query);
$matches = array();
foreach ($pieces as $piece) {
list($key, $value) = explode('=', $piece);
$matches[substr($key, 5, -1)] = $value;
}
Below is the response I'm getting after posting to an API.... I don't think parse_url is going to cut it. Are there any built in PHP functions or better ways to turn this into an array? This is the output of var_dump
sting(163) "response=3&responsetext=Duplicate transaction REFID:115545335&authcode=&transactionid=&avsresponse=&cvvresponse=&orderid=&type=auth&response_code=300&processor_id="
Use parse_str() with the optional $arr parameter.
Parses str as if it were the query string passed via a URL
You are looking for parse_str.
It turns a query string into an associative array.
I propose :
$elements = explode('&', $input);
$data = array();
foreach($elements as $e) {
$d = explode('=', $e);
$data[$d[0]] = isset($d[1]) ? $d[1] : '';
}
But maybe there is a better way.