clearing the link id - php

if we have
$id = 39827-key1-key2-key3
and we want to show only the number or anything before (-)
then by using
$realid = array_shift(explode("-", $id));
we will get echo $realid; // 39827
Now my problem is as following !
if we have $id = key1/key2
and i want any way that remove the whole part key1/ and gives me only key2
how can i do it?

Ok, from your comment above, I'm assuming you want to do something like:
$id = "key1/key2";
$result = ???;
// Now $result=="$key2"
Why not just:
$parts = explode("/", $id);
$result = $parts[1];

Using the strstr() function, which was created exactly for things like this:
$id = 'key1/key2';
$realid = strstr($id, '/', true);
Do note that you have to be running PHP 5.3 or newer for this to work.

confusing question. my interpretation for $rawId containing the '/' char:
$rawId = 'key1/key2';
$realId = substr($rawId, 1 + strpos($rawId, '/')); // key2

Yet another way:
$result = implode('', array_slice(explode('/', $id), 1, 1));

Related

Get URL and remove id from it

I have a url like this
url:- url.php?gender=male&&grand=brand1&&id=$id
eg. $id may be 1, 100 ,23, 1000 any number
I am getting the url using
<?php echo $_SERVER['REQUEST_URI']; ?>
Is it possible to change the id and make the url like
url:- url.php?gender=gender&&brand=brand1&&id=$newId
where $newId can be any number except the one that is present in the url
function remove_querystring_var($url, $key) {
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -2);
return $url;
}
this will do the job, pass your url and key you want to remove in this function
ex remove_querystring_var("url.php?gender=male&&grand=brand1&&id=$id","id"), it will remove id from your url
Get the id position and the remove the id using sub string.
$url = $_SERVER['REQUEST_URI'];
#Get id position and remove && by subtracting 2 from length
$pos = strrpos($url,'id') - 2;
$url = substr($url, 0, $Pos);
echo $url;
You could use $_SERVER['QUERY_STRING'] instead.
Moreover, if your 'id' value is not always at the end, getting a substr up to it wouldn't be very robust. Instead turn it into an associative array and fiddle with it.
For example, starting with /url.php?gender=male&grand=brand1&id=999&something=else
parse_str($_SERVER['QUERY_STRING'], $parsed);
unset($parsed['id']);
// there may be a better way to do this bit.
$new_args = [];
foreach($parsed as $key=>$val){
$new_args[] = "$key=$val";
}
$new_arg_str = join($new_args, '&');
$self = $_SERVER['PHP_SELF'];
$new_endpoint = "$self?$new_arg_str";
echo $new_endpoint;
result: /url.php?gender=male&grand=brand1&something=else
Bit more legible than regex as well.
Bear in mind if you're going to redirect (using header("Location: whatever") or otherwise), you'll need to be wary of redirect loops. An if statement could avoid that.
References:
http://php.net/manual/en/reserved.variables.server.php
http://php.net/manual/en/function.parse-str.php
http://php.net/manual/en/function.unset.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.join.php

Parse transfermarket link

how to get ID(the numbers at the end) from links transfermarket site in PHP?
for example http://www.transfermarkt.co.uk/claudio-bravo/profil/spieler/40423
$url = 'http://www.transfermarkt.co.uk/andriy-pyatov/profil/spieler/40423';
$r = parse_url($url);
$endofurl = substr($r['path'], strrpos($r['path'], '/'));
$endofurl returns /40423
how to get rid of / ?
Solution A
Assuming
$url = "http://www.transfermarkt.co.uk/andriy-pyatov/profil/spieler/40423";
you could use explode to split the url and then end to get the last element (40423 in this example):
$id = explode("/", $url);
$id = end($id);
Solution B
In case you really want to use $endofurl:
$id = substr($endofurl, 1);

Remove parameter from link

I have many links with parameter number - value is numbers between 1-1000
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
How can i remove from this parameter and value with PHP? I would like receive:
http://mysite.com?one=2&two=4
http://mysite.com?one=2&two=4&four=4
http://mysite.com?one=2&three=4
http://mysite.com?two=4
http://mysite.com?one=2&two=4
Try this:
$str = 'http://mysite.com?one=2&two=4&number=2';
$url = parse_url($str);
parse_str($url['query'], $now );
unset($now['number']);
foreach($now as $key=>$value) :
if(is_bool($value) ){
$now[$key] = ($value) ? 'true' : 'false';
}
endforeach;
$options_string=http_build_query($now);
echo $url = 'http://mysite.com?'.$options_string;
Reference : PHP function to build query string from array - not http build query
Like this
$urls = '
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
';
echo '<pre>';
echo preg_replace('#&number=\d+#', '', $urls);
you can build a redirection after building a new URL with $_GET['one']
Use bellow steps,this is clear aproach
1- Parse the url into an array with parse_url()
2- Extract the query portion, decompose that into an array
3- Delete the query parameters you want by unset() them from the array
4- Rebuild the original url using http_build_query()
hope this help you
You could use parse_str() which parses the string into variables. In that way you can separate them easily
I wrote example of code.
<?php
$arr = array();
$arr[] = 'http://mysite.com?one=2&two=4&number=2';
$arr[] = 'http://mysite.com?one=2&two=4&four=4&number=124';
$arr[] = 'http://mysite.com?one=2&three=4&number=9';
$arr[] = 'http://mysite.com?two=4&number=242';
$arr[] = 'http://mysite.com?one=2&two=4&number=52';
function remove_invalid_arguments(array $array_invalid, $urlString)
{
$info = array();
parse_str($urlString, $info);
foreach($array_invalid as $inv)
if(array_key_exists($inv,$info)) unset($info[$inv]);
$ret = "";
$i = 0;
foreach($info as $k=>$v)
$ret .= ($i++ ? "&" : ""). "$k=$v"; //maybe urlencode also :)
return $ret;
}
//usage
$invalid = array('number'); //array of forbidden params
foreach($arr as $k=>&$v) $v =remove_invalid_arguments($invalid, $arr[1]);
print_r($arr);
?>
Working DEMO
If "&number=" is ALWAYS after the important parameters, I'd use str_split (or explode).
The more sure way is to use parse_url(),parse_str() and http_build_query() to break the URLs down and put them back together.
As per example of your url -
$s='http://mysite.com?one=2&two=4&number=2&number2=200';
$temp =explode('&',$s);
array_pop($temp);
echo $newurl = implode("&", $last);
Output is :http://mysite.com?one=2&two=4&number=2
Have a look at this one using regex: (as an alternative, preferably use a parser)
(.+?)(?:&number=\d+)
Assuming &number=2 is the last parameter. This regex will keep the whole url except the last parameter number

php getting part of a URL into a string

Hi guys i m using this code to get the id on my url
$string = $url;
$matches = array();
preg_match_all('/.*?\/(\d+)\/?/s', $string, $matches);
$id = $matches[1][0];
this code works for urls like
http://mysite.com/page/1
http://mysite.com/page/somepage/2
http://mysite.com/page/3/?pag=1
i will have id = 1 / id = 2 / id = 3
but for a url like this
http://mysite.com/page/122-page-name/1
this returns id = 122
THe id i m try to get always will be the last part of the url or will have /?p= after
so the urls type i can have
http://mysite.com/page/1
http://mysite.com/page/some-page/2
http://mysite.com/page/12-some-name/3
http://mysite.com/page/some-page/4/?p=1
http://mysite.com/page/13-some-page/5/?p=2
id = 1 / id = 2 / id = 3 / id = 4 / id = 5
If your id will always be located at the end of your url, you could explode the contents of your url and take the last element of the resulting array. If it may include variables (like ?pag=1) you can add a validation after the explode to check for the variable.
$urlArray = explode('/', $url);
$page = end($urlArray);
if(strpos($page, 'pag')!==false){
//get the contents of the variable from the $page variable
//exploding the variable through the ? variable and getting
//the numeric characters at the end
}
I would favor URL parsing over trying to use a regex, especially if you have a wide variety of (valid) URLs to deal with.
end(array_filter(explode('/', parse_url($url, PHP_URL_PATH))));
The array_filter deals with the trailng slash.
Since it's always at the end or has ?p=x after it you can do the following:
$params = explode('/', $_SERVER['REQUEST_URI']);
$c = count($params);
if (is_int($params[$c - 1])
$id = $params[$c - 1];
else
$id = $params[$c - 2];
Not a direct answer, more of a "how to work this out for yourself" answer :]
Place this code at the top of your page, before anything else (but after <?php)
foreach($_SERVER as $k => $v) {
echo $k.' = '.$v.'<br />';
}
exit;
Now load up each of the different URIs in a different tab and look at the results. You should be able to work out what you need to do.

Doing a substring operation based on a regex in PHP

In Python, I can do substring operations based on a regex like this.
rsDate = re.search(r"[0-9]{2}/[0-9]{2}/[0-9]{4}", testString)
filteredDate = rsDate.group()
filteredDate = re.sub(r"([0-9]{2})/([0-9]{2})/([0-9]{4})", r"\3\2\1", filteredDate)
What's the PHP equivalent to this?
You could simply use the groups to build your filteredDate :
$groups = array();
if (preg_match("([0-9]{2})/([0-9]{2})/([0-9]{4})", $testString, $groups))
$filteredDate = sprintf('%s%s%s', $groups[3], $groups[2], $groups[1]);
else
$filteredDate = 'N/A';
so you want a replace...
$filteredDate = preg_replace("([0-9]{2})/([0-9]{2})/([0-9]{4})","$3$2$1",$testString);
Try this:
$result = preg_replace('#([0-9]{2})/([0-9]{2})/([0-9]{4})#', '\3\2\1' , $data);

Categories