I have a strings like this:
index.php?url=index/index
index.php?url=index/index/2&a=b
I'm trying to get this part of string: index/index or index/index/2.
I have tried parse_str function but not successful.
Thanks.
You should be able to use $_SERVER['QUERY_STRING'] as shown below:
$url_params = $_SERVER['QUERY_STRING']; // grabs the parameter
$url_params = explode( '/', $url_params ); // seperates the params by '/'
which returns an array
Example index.php?url=index/index2 now becomes:
$url_params[ 0 ] = index;
$url_params[ 1 ] = index2;
Without more info:
// Example input
$input = "index.php?url=index/index/2&a=b";
$after_question_mark = explode("=",$input)[1];
$before_ampersand = explode("&",$after_question_mark)[0];
$desired_output = $before_ampersand; // 'index/index/2'
More resilient option:
// Example input
$input = "index.php?url=index/index/2&a=b";
$after_question_mark = explode("=",$input)[1];
if (strstr($after_question_mark, "&")){
// Check for ampersand
$before_ampersand = explode("&",$after_question_mark)[0];
$desired_output = $before_ampersand; // 'index/index/2'
} else {
// No ampersand
$desire_output = $after_question_mark;
}
$url = "index.php?url=index/index/2&a=b";
$query = parse_url($url, PHP_URL_QUERY);
$output = substr($query, $strpos($query, "=") + 1);
output: index/index/2&a=b
This will get you everything after the question mark
You can get more info on parse_url
or
$url = "index.php?url=index/index/2&a=b";
$output = substr($url, strpos("=") +1, $strrpos($url, "&") - strlen($url));
output: index/index/2
You dont need to break into an array to create overhead if you really just want to get a substring from a string
this will return false on no query string
Related
I have this code, the part I am looking for is the number from the url 1538066650683084805
I use this example
$tweet_url = 'https://twitter.com/example/status/1538066650683084805'
$arr = explode("/", $tweet_url);
$tweetID = end($arr);
Which works however sometimes on phones, When people copy and paste the url it has parameters on the end of it like this;
$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
When a URL is exploded with the URL above the code doesn't work, how do I get the number 1538066650683084805 in both uses.
Thanks so much.
I would suggest using parse_url to get just the path, then separate that out:
$url = parse_url('https://twitter.com/example/status/1538066650683084805?q=2&t=1');
/*
[
"scheme" => "https",
"host" => "twitter.com",
"path" => "/example/status/1538066650683084805",
"query" => "q=2&t=1",
]
*/
$arr = explode("/", $url['path']);
$tweetID = end($arr);
I would explode first on the question mark and just look at the index 0 .. THEN explode the slash ...
$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
$tweet_url = explode('?', $tweet_url)[0];
$arr = explode("/", $tweet_url);
$tweetID = end($arr);
If the question mark does not exist -- It will still return the full URL in $tweet_url = explode('?', $tweet_url)[0]; so it's harmless to have it there.
And this is just me .. But I would write it this way:
$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
$tweetID = end(
explode("/",
explode('?', $tweet_url)[0]
)
);
echo $tweetID . "\n\n";
I'm not sure it's even the right way to define this question.
I have string that may be exist, and may not. It happens to be a number: $number
If $number doesn't exist, then I want to use the PHP variable $url.
But if $number does exist, then I want to use the PHP variable which is named $url+the number, i.e, $url2 if $number=2
So I tried this code, but it doesn't work:
$number = "2"; //(Can be either missing, or equal to 1, 2, or 3)
$url = "www.0.com"; // Fallback
$url1 = "www.1.com";
$url2 = "www.2.com";
$url3 = "www.3.com";
$result = $url.=$number ;
// If $number=1, I want $result to be : www.1.com
// If $number=2, I want $result to be : www.2.com
// If $number=3, I want $result to be : www.3.com
// If $number IS NOT SET, I want $result to be : www.0.com
// Now do something with $result
Perhaps there's a completely better way to achieve what I want (will be happy to see example), but anyway I'm curious as well to understand how to achieve it my way.
Okay, so you're talking about a variable variable.
You should define the name of the variable you need to use in a string, and then pass that to a variable variable using $$ syntax:
if( isset($number) && is_numeric($number) )
{
$name = 'url'.$number;
$result = $$name;
}
else
{
$result = $url;
}
That having been said, you may be better off using an array for this:
$urls = [ 'www.0.com', 'www.1.com', 'www.2.com', 'www.3.com' ];
$result = (!isset($number)) ? $urls[0] : $urls[ intval($number) ];
You can use ternary with in_array and empty.
$number = "2"; //(Can be either missing, or equal to 1, 2, or 3)
$url = "www.0.com"; // Fallback
$url1 = "www.1.com";
$url2 = "www.2.com";
$url3 = "www.3.com";
$result = (!empty($number) && in_array($number, array(1,2,3))) ? ${'url' . $number} : $url;
echo $result;
Demo: https://eval.in/821737
In php you can have things like dynamic variable names:
$variableName = "url".$number;
$result = $$variableName;
However, you should make sure, that $variableName refers to an existing variable:
$result = "www.fallbackURL.com";
if(isset($$variableName)) $result = $$variableName;
Or Try this code:
$number = 5;
$url[0] = "www.0.com"; // Fallback
$url[1] = "www.1.com";
$url[2] = "www.2.com";
$url[3] = "www.3.com";
if (!isset($number)) $number=0;
if (!isset($url[$number])) $number=0;
$result = $url[$number];
If you add $ front of string, it define variable, so you can use following code:
<?php
$number = "2"; //(Can be either missing, or equal to 1/2/3)
$url = "www.0.com"; // Fallback
$url1 = "www.1.com";
$url2 = "www.2.com";
$url3 = "www.3.com";
if(isset($number) && is_numeric($number) && $number <= 3) {
$variable_name = 'url' . $number; //string like url2
} else {
$variable_name = 'url';
}
$result = $$variable_name ; //define $url2 from url2 string
echo $result;
// Now do something with $result
Example for define variable with string variable:
$string = 'hello';
$$string = 'new variable'; //define $hello variable
echo $hello; //Output: "new variable"
if the url need just a number, you can do this easy way
($number)?$number:0;
$url = "www.".$number.".com";
if there are specific real url, you can use array
$array[0] = "www.google.com";
$array[1] = "www.facebook.com";
($number)?$number:0;
url = $array[$number];
Updated code:
$number = "2";
if(isset($number)){
$res = "url".$number;
$result=$$res;
}else{
$result=$url;
}
echo $result;
I want to extract all used parameters of a link as a text string. Example:
$link2 = http://example.com/index.html?song=abcdefg;
When using the above link $param should give out all the parameters '?song=abcdefg'. Unfortunately I do not know the id index.html nor the parameters and their respective data values.
As much as I am informed there is the function $_GET, which creates an array, but I need a string.
You can use parse_url:
$link2 = 'http://example.com/index.html?song=abcdefg';
$param = '?' . parse_url($link2, PHP_URL_QUERY);
echo $param;
// ?song=abcdefg
Many librairies exist to parse url, you can use this one for an exemple :
https://github.com/thephpleague/uri
use League\Uri\Schemes\Http as HttpUri;
$link2 = 'http://example.com/index.html?song=abcdefg';
$uri = HttpUri::createFromString($link2);
// then you can access the query
$query = $uri->query;
You also can try this one :
https://github.com/jwage/purl
A weird way to do this is
$link2 = 'http://example.com/index.html?song=abcdefg';
$param = strstr($link2, "?");
echo $param // ?song=abcdefg
strstr($link2, "?") will get everything after the first position of ?; including the leading ?
you can loop over the get array and parse it into a string:
$str = "?"
foreach ($_GET as $key => $value) {
$temp = $key . "=". $value . "&";
$str .= $temp
}
rtrim($str, "&")//remove leading '&'
You can use http_build_query() method
if ( isset ($_GET))
{
$params = http_build_query($_GET);
}
// echo $params should return "song=abcdefg";
With $_SERVER['REQUEST_URI'], I get a URL that could be:
index.php
or
index.php?id=x&etc..
I'd like to do two things:
Find if there is a ?something after index.php name with regular expression.
If there is in the url a specific var (id=x) and delete it from the url.
For example:
index.php?id=x => index.php
index.php?a=11&id=x => index.php?a=11
How can I do this?
To check if there is a ?something after index.php, you could use the built-in function parse_url(), like so:
if (parse_url($url, PHP_URL_QUERY)) {
// ?something exists
}
To remove the id, you could use parse_str(), get the query parameters, store them in an array, and unset the particular id.
And since you also want to re-create the URL after the particular element is deleted from the query part of the URL, then you could use http_build_query().
Here's a function for that:
function removeQueryString($url, $toBeRemoved, $match)
{
// check if url has query part
if (parse_url($url, PHP_URL_QUERY)) {
// parse_url and store the values
$parts = parse_url($url);
$scriptname = $parts['path'];
$query_part = $parts['query'];
// parse the query parameters from the url and store it in $arr
$query = parse_str($query_part, $arr);
// if id == x, unset it
if (isset($arr[$toBeRemoved]) && $arr[$toBeRemoved] == $match) {
unset($arr[$toBeRemoved]);
// if there less than 1 query parameter, don't add '?'
if (count($arr) < 1) {
$query = $scriptname . http_build_query($arr);
} else {
$query = $scriptname . '?' . http_build_query($arr);
}
} else {
// no matches found, so return the url
return $url;
}
return $query;
} else {
return $url;
}
}
Test cases:
echo removeQueryString('index.php', 'id', 'x');
echo removeQueryString('index.php?a=11&id=x', 'id', 'x');
echo removeQueryString('index.php?a=11&id=x&qid=51', 'id', 'x');
echo removeQueryString('index.php?a=11&foo=bar&id=x', 'id', 'x');
Output:
index.php
index.php?a=11
index.php?a=11&qid=51
index.php?a=11&foo=bar
Demo!
If it must be a regular expression :
$url='index.php?a=11&id=1234';
$pattern = '#\id=\d+#';
$url = preg_replace($pattern, '', $url);
echo $url;
output
index.php?a=11&
There is a trailing &, but the above removes any id=xxxxxxxx
Want to remove p2variable from url string, below are 3 cases if case 3 also remove ? sign.
case 1: http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p1=xyz&p3=ghj
case 2: http://www.domain.com/myscript.php?p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p3=ghj
case 3: http://www.domain.com/myscript.php?p2=10
result: http://www.domain.com/myscript.php
Want to achieve result with single preg_replace expression.
Don't use regular expressions when dealing with URL values. It's much easier (and safer) to handle them as a URL instead of plain text.
This could be one way to do it:
Split the url first and parse the query string
Take the parameter out
Rebuild the url
The below code is an example of such an algorithm:
// remove $qs_key from query string of $url
// return modified url value
function clean_url_qs($url, $qs_key)
{
// first split the url in two parts (at most)
$parts = explode('?', $url, 2);
// check whether query string is passed
if (isset($parts[1])) {
// parse the query string into $params
parse_str($parts[1], $params);
// unset if $params contains $qs_key
if (array_key_exists($qs_key, $params)) {
// remove key
unset($params[$qs_key]);
// rebuild the url
return $parts[0] .
(count($params) ? '?' . http_build_query($params) : '');
}
}
// no change required
return $url;
}
Test code:
echo clean_url('http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10', 'p2'), "\n";
Found this in one of my old projects (a bit of shitcode, but...), may help you:
$unwanted_param = 'p2';
$s = 'http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj';
$s = parse_url($s);
$params = explode('&', $s['query']);
$out_params = array();
foreach ($params as $key => &$param) {
list($name, $value) = explode('=', $param);
if ($unwanted_param == $name) {
unset($params[$key]);
} else {
$out_params[$name] = $value;
}
}
$query = '?' . http_build_query($out_params);
$result = $s['scheme'] . '://' . $s['host'] . $s['path'] . $query;
var_dump($result);
Using preg_replace, something like
$url = preg_replace('!([\?&]p2=[^&\?$]+)!i', '', $url);
However, personally I'd do the following
if (strpos($url, '?') !== false) {
list($domain, $qstring) = explode('?', $url, 2);
parse_str($qstring, $params);
if (isset($params['p2'])) {
unset($params['p2']);
}
$qstring = !empty($params) ? '?' . http_build_query($params) : '';
$url = $domain . $qstring;
}