I have a string like this :
oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc
How can I extract the two variables oauth_token and oauth_token_secret from the about string using PHP
NOTE: this is not coming from the URL( we can do that using $_GET)
Thank YOU
Use parse_str() for parsing query string parameters.
// Extract into current scope, access as if they were PHP variables
parse_str($str);
echo $oauth_token;
echo $oauth_token_secret;
// Extract into array
parse_str($str, $params);
echo $params['oauth_token'];
echo $params['oauth_token_secret'];
You may wish to urldecode() the variables after you've extracted them.
try this
$text = "oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc"
;
$i=explode('&',$text);
$j=explode('=',$i[0]);
$k=explode('=',$i[1]);
echo $j[0]."<br>";
echo $j[1]."<br>";
echo $k[0]."<br>";
echo $k[1]."<br>";
1, split the two parts of the $string,
$str_array = explode('&',$string);
2, get the part after the "=" sign, so for the oauth_token part:
$oauth_token_array = explode('=',$str_array[0]);
$oauth_token = $oauth_token_array[1];
EDIT: ignore this, it's definitely verbose. BoltClock's the solution.
The best way (most reusable) is to use a function which returns an array similar to $_GET.
edit There is already a function for this: http://www.php.net/manual/en/function.parse-str.php This will work with array get values too.
$values = array();
parse_str($query_strng, $values);
Quite an ugly function, why can't it just return the array of values. It either stuffs them into individual variables or you need to pass in a reference. Come on php, you can do better. /rant
Related
I have an object and need to access an attribute from a string like this:
$string = 'items[0]->sellers[0]->commertialOffer->Price';
I've tried something like this but it doesn't work:
$myObject->{$string};
Any idea?
$items = '{"items":[{"sellers":[{"commertialOffer":{"Price":33}}]}]}';
$myObject = json_decode($items);
$string = 'items[0]->sellers[0]->commertialOffer->Price';
echo ($myObject->{'items'}[0]->{'sellers'}[0]->{'commertialOffer'}->{'Price'});
echo ($myObject->items[0]->sellers[0]->commertialOffer->Price);
As $myObject->items is an array you can`t access it like
$string = 'items[0]';
echo $myObject->{$string};
You can access that by using
$string = 'items';
echo $myObject->{$string}[0];
Are you passing the string between two functions ? If yes , then take 4 values and create the string like :-
$string = $value1.'|'.$value2.'|'.$value3.'|'.$value4 ;
Then explode the string and get back the 4 values .
You probably want to revise your problem because interpreting raw code from a string is often a bad idea. You could potentially use the eval function: see. Again, this is probably not a good idea: when is eval evil?
I'm trying to pull a string from my URL in WordPress, and create a function around it in the functions file.
The URL is:
"https://made-up-domain.com/?page_id=2/?variables=78685,66752"
My PHP is:
$string = $_GET("variables");
echo $string;
So I'm trying to return "78685,66752". Nothing happens. Is the first question mark a problem? Or what am I doing incorrectly? Thanks!
$_GET should be in the form
$string = $_GET["variables"];
and not
$string = $_GET("variables");
$_GET is not a function but an Array so correct way of reading it is
$string = $_GET['variables'];
You are also creating the query string all wrong, you should be using
?variables=123,456&page=1
Read more about $_GET here http://php.net/manual/en/reserved.variables.get.php
Your URL should be like:
https://made-up-domain.com/?page_id=2&variables=78685,66752
instead of:
https://made-up-domain.com/?page_id=2/?variables=78685,66752
& char is separating the queries in URL.
And you have syntax error. Use $string = $_GET["variables"]; because $_GET is a superglobal array, not a function.
Use $variables = explode(",", $string); separate values into an array if you want. Simplier way is $variables = explode(",", $_GET["variables"]);
You should format your href and get parameter like this
http://example.com/mypage.html?var1=value1&var2=value2&var3=value3
+ Edit your get method syntax
$string = $_GET['variables'];
I have this string:
solutions.php?id=80d28c22-68d9-11e3-af95-742f689f29f1
How can I extract just the part of the id, just the value of the ID, the
80d28c22-68d9-11e3-af95-742f689f29f1
I tried the substring function of PHP, the problem is I'm still figuring out how to tell it that it's all the way till the end of the string.
This is what I have so far:
$_solutionID = substr($_currentURL, 17, ??);
try this:
$id = $_GET['id'];
That should work :)
You can retrieve that value from the GET superglobal array: $_GET['id']
You can use $_GET variable for your purpose:
echo $_GET['id'];
# => 80d28c22-68d9-11e3-af95-742f689f29f1
$_GET is a superglobal that is available anywhere in a PHP script, and can be used to check the values of query parameters in a URL, i.e. it stores an associative array of all query parameters of the current page URL.
Also, for reference, if you happen to issue a POST request and would like to find the data that was posted to that URL, you can use $_POST variable in exactly the same manner as the $_GET variable.
I suggest you to use parse_url to extract the query (after the '?') and a regex to extract the id after the 'id='.
$parts = parse_url('solutions.php?id=80d28c22-68d9-11e3-af95-742f689f29f1');
$query = $parts['query'];
$matches = array();
if (preg_match('/id=([-0-9a-z]+)/', $query, $matches) {
return $matches[1];
}
ok, So I have this array:
$choices = array($_POST['choices']);
and this outputs, when using var_dump():
array(1) { [0]=> string(5) "apple,pear,banana" }
What I need is the value of those to become variables as well as adding in value as the string.
so, I need the output to be:
$apple = "apple";
$pear = "pear";
$banana = "banana";
The value of the array could change so the variables have to be created depending on what is in that array.
I would appreciate all help. Cheers
Mark
How about
$choices = explode(',', $_POST['choices']);
foreach ($choices as $choice){
$$choice = $choice;
}
$str = "apple,pear,pineapple";
$strArr = explode(',' , $str);
foreach ($strArr as $val) {
$$val = $val;
}
var_dump($apple);
This would satisfy your requirement. However, here comes the problem, since you could not predefine how many variables are there and what are they, it's hard for you to use them correctly. Test "isset($VAR)" before using $VAR seems to be the only safe way.
You'd better just split the source string in just one array and just operate the elements of the specific array.
I have to concur with all the other answers that this is a very bad idea, but each of the existing answers uses a somewhat roundabout method to achieve it.
PHP provides a function, extract, to extract variables from an array into the current scope. You can use that in this case like so (using explode and array_combine to turn your input into an associative array first):
$choices = $_POST['choices'] ?: ""; // The ?: "" makes this safe even if there's no input
$choiceArr = explode(',', $choices); // Break the string down to a simple array
$choiceAssoc = array_combine($choiceArr, $choiceArr); // Then convert that to an associative array, with the keys being the same as the values
extract($choiceAssoc, EXTR_SKIP); // Extract the variables to the current scope - using EXTR_SKIP tells the function *not* to overwrite any variables that already exist, as a security measure
echo $banana; // You now have direct access to those variables
For more information on why this is a bad approach to take, see the discussion on the now deprecated register_globals setting. In short though, it makes it much, much easier to write insecure code.
Often called "split" in other langauges, in PHP, you'd want to use explode.
EDIT: ACTUALLY, what you want to do sounds... dangerous. It's possible (and was an old "feature" of PHP) but it's strongly discourage. I'd suggest just exploding them and making their values the keys of an associative array instead:
$choices_assoc = explode(',', $_POST['choices']);
foreach ($choices as $choice) {
$choices_assoc[$choice] = $choice;
}
why I get error when I pass the string with something like 'form.php?', for instance,
parse_str('form.php?category=contacts');
echo $category;
I get this,
Notice: Undefined variable: category in C:\wamp\www\1hundred_2011_MVC\applications\CMS\category_manage.php on line xx
but,
parse_str('category=contacts');
echo $category;
I get what I want,
contacts
how can I fix it? I have to pass something like 'xxx.php?category=contacts' to get 'contacts' or something in the variable.
thanks.
The function parse_str only parses the query string, not the entire URL. Try using parse_url with the component set to PHP_URL_QUERY to extract the query string first, then use parse_str on that.
$url_query = parse_url('form.php?category=contacts', PHP_URL_QUERY);
parse_str($url_query, $output);
echo $output['category'];
Result:
contacts
See it at ideone.
parse_str will only accept query strings:
$q = 'foo?hello=world';
parse_str($q);
echo ${'foo?hello'}; // outputs 'world'
Strip the beginning of the URL first:
$q = 'foo?hello=world';
parse_str(substr($q, strpos($q, '?')+1);
echo $hello; // outputs 'world'
Consider using parse_str second argument to have the data in an array instead, to avoid overwriting local variables.
You may want to use urldecode plus return extracted variables like so:
... some helper class...
/**
* Return parsed serialized JQuery object as PHP array of extracted variables
*/
protected static function parseFields($encoded){
parse_str(urldecode($encoded));
unset($encoded);
return get_defined_vars();
}
Also, you may want to utilize the JQuery function "$.param(data)" for creating URL encoded string:
var encoded=$.param(fields);
and submit via AJAX/POST request to server to function parseFields().