Is there a way I can strip out the variables from a link using PHP for example, if I have a link that reads http://localhost/link/index.php?s=30&p=3 how would I strip out ?s=30&p=3 so my link reads http://localhost/link/index.php
list($url) = explode("?", $longUrl, 2);
Edit (suggested by Hoohah):
Also you can use strstr() (PHP 5.3.0 onward):
echo strstr($longurl, "?", TRUE);
PHP has a built in function for this.
It is parse_url(). Take a look at the possible return values. In this case we can use scheme, host, and path.
For example:
<?php
$info = parse_url("http://localhost/link/index.php?s=30&p=3");
echo $info["scheme"] . "://" . $info["host"] . $info["path"];
// Output: http://localhost/link/index.php
?>
Live example
The advantage of this method over using explode() is that it gives you control over whether you want to show the username, password, and port if included. The code above will not show any of these, so http://user:pass#localhost:81/link/index.php?s=30&p=3 will return http://localhost/link/index.php, stripping the username, password, and port number, which is what I assume you'd want. Username, password, and port are available as $info["user"], $info["pass"], and $info["port"].
The explode() method fails if the password contains question marks. This method doesn't fail even with ? and # signs in the password.
As a final note, if you are going to be dealing with port numbers, usernames, and passwords, you can use the code below (which has one added line) to strip usernames and passwords but keep port number:
<?php
$info = parse_url("http://user:__?**####&?ss#localhost:80/link/index.php?s=30&p=3");
// If port is present add a colon before it, if not make it an empty string.
isset($info["port"]) ? $port = ":" . $info["port"] : $port ="";
echo $info["scheme"] . "://" . $info["host"] . $port . $info["path"];
// Outputs: http://localhost:80/link/index.php
?>
Live example
Finally, you really should not be using username and password in the link. From RFC2396
Some URL schemes use the format "user:password" in the userinfo
field. This practice is NOT RECOMMENDED, because the passing of
authentication information in clear text (such as URI) has proven to
be a security risk in almost every case where it has been used.
Try this:
$pos = strpos($url, '?');
if($pos !== FALSE) {
$url = substr($url, 0, $pos);
}
$url = 'http://localhost/link/index.php?s=30&p=3';
$d = explode("?", $url);
$stripped = reset($d);
$fullUrl = "http://localhost/link/index.php?s=30&p=3#dontreplace";
$urlData = parse_url($fullUrl);
$url = str_replace('?'.$urlData['query'],'',$fullUrl);
This solution takes into account that you could have a hashtag after the paremeters and it does not replace it.
If you just don't care of what is after the ? then use the other answers
$url = strtok($url,"?");
I haven't tested this but you could probably do something like:
$my_url = 'http://localhost/link/index.php?s=30&p=3';
$split = explode('?', $my_url);
$new_url = $split[0];
parse_url('http://localhost/link/index.php?s=30&p=3',PHP_URL_PATH);
If U need to parse the requested url, U can simply take it from globals:
// http://localhost/foo/bar?foo=bar&Foo1=Bar1
var_dump($_SERVER['QUERY_STRING']); // string(17) "foo=bar&Foo1=Bar1"
If symfony/http-foundation component is used, U can get query string from its Request class as follows:
$request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
$queryString = $request->getQueryString();
Related
I have easy question. I need to verify a string and validate a whitelist domain like this:
$WList = array('mega.co.nz','mediafire.com','putlocker.com','');
$Dominio = str_replace("www.","",parse_url($EnlaceUrl,PHP_URL_HOST));
if(in_array($Dominio,$WList)){//ok}
but this method doesnt retieve me domains like:
www42.zippyshare.com,www51.zippyshare.com,www71.zippyshare.com,www23.zippyshare.com
how resolve this problem? :)
Try this which removes all that begin with www until the first dot (inclusive):
$Dominio = preg_replace('~^www[^.]*\.~', '', parse_url($EnlaceUrl,PHP_URL_HOST));
You can use this:
if (preg_match('/[\w\d-]+\.(\w{3,4}|(\w{2,3}\.\w{2}))$/', $Dominio, $match))
$Dominio = $match[1];
It will convert anything.domainname.suffix into domainname.suffix so you can test against your list.
Yet another preg_match example :
if(preg_match("/(?:([^.]+).)?([^.]+).([^\\/]+)/", $Dominio, $m)) {
$Dominio = $m[2] . '.' $m[3];
}
How i can get a hash or any text from URL after the question mark.
For example "http://mediafire.com/?lmle92c5l50uuy5"
I want to get the hash "lmle92c5l50uuy5"
Try $_SERVER superglobal if you want to get "hash" for current URL:
echo $_SERVER['QUERY_STRING'];
If you really need to parse not your URL, you might also use strstr() + ltrim():
$url = "http://mediafire.com/?lmle92c5l50uuy5";
echo ltrim(strstr($url, '?'), '?');
Shows:
lmle92c5l50uuy5
Also possible to use explode() (as mentioned in #Shubham's answer), but make it shorter with list() language construction:
$url = "http://mediafire.com/?lmle92c5l50uuy5";
list(, $hash) = explode('?', $url);
echo $hash;
Use explode().
$arr = explode("?", "http://mediafire.com/?lmle92c5l50uuy5");
$hash = $arr[1];
Or,
You can use parse_url() too.
$hash = parse_url("http://mediafire.com/?lmle92c5l50uuy5", PHP_URL_QUERY);
I have this string:
$str="http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
Is there a built-in php function that can shorten it by removing the ._SL110_.jpg part, so that the result will be:
http://ecx.images-amazon.com/images/I/418lsVTc0aL
no, there's not any built in URL shortener php function, if you want to do something similar you can use the substring or create a function that generates a short link and stores the long and short value somewhere in database and display only the short one.
well, it depends if you need a regexp replace (if you don't know the complete value) or if you can do a simple str_replace like below:
$str = str_replace(".SL110.jpg", "", "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg");
You can use preg_replace().
For example preg_replace("/\.[^\.]+\.jpg$/i", "", $str);
I would recommend using:
$tmp = explode("._", $str);
and then using $tmp[0] for your purpose, if you make sure the part you want to get rid of is always separated by "._" (dot-underscore) symbols.
You can try
$str = "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
echo "<pre>";
A.
echo strrev(explode(".", strrev($str), 3)[2]) , PHP_EOL;
B.
echo pathinfo($str,PATHINFO_DIRNAME) . PATH_SEPARATOR . strstr(pathinfo($str,PATHINFO_FILENAME),".",true), PHP_EOL;
C.
echo preg_replace(sprintf("/.[^.]+\.%s$/i", pathinfo($str, PATHINFO_EXTENSION)), null, $str), PHP_EOL;
Output
http://ecx.images-amazon.com/images/I/418lsVTc0aL
See Demo
you could do this substr($data,0,strpos($data,"._")), if what you want is to strip everything after "._"
No, it is not (at least not directly). Such URL shorteners usually generate unique ID and remember your original URL and generated ID. When you enter such url, you start a script, which looks for given ID and then redirect to target URL.
If you want just cut of some portion of your string, then assuming that filename format is as you shown, just look for 1st dot and substr() to that place. Or
$tmp = explode('.', $filename);
$shortName = $tmp[0];
If suffix ._SL110_.jpg is always there, then simply str_replace('._SL110_.jpg', '', $filename) could work.
EDIT
Above was example for filename only. Whole code would be:
$url = "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
$urlTmp = explode('/', $url);
$fileNameTmp = explode( '.', $urlTmp[ count($urlTmp)-1 ] );
$urlTmp[ count($urlTmp)-1 ] = $fileNameTmp[0];
$newUrl = implode('/', $urlTmp );
printf("Old: %s\nNew: %s\n", $url, $newUrl);
gives:
Old: http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg
New: http://ecx.images-amazon.com/images/I/418lsVTc0aL
i have this URI.
http://localhost/index.php?properties&status=av&page=1
i am fetching basename of the URI using following code.
$basename = basename($_SERVER['REQUEST_URI']);
the above code gives me following string.
index.php?properties&status=av&page=1
i would want to remove the last variable from the string i.e &page=1. please note the value for page will not always be 1. keeping this in mind i would want to trim the variable this way.
Trim from the last position of the string till the first delimiter i.e &
Update :
I would like to remove &page=1 from the string, no matter in which position it is on.
how do i do this?
Instead of hacking around with regular expression you should parse the string as an url (what it is)
$string = 'index.php?properties&status=av&page=1';
$parts = parse_url($string);
$queryParams = array();
parse_str($parts['query'], $queryParams);
Now just remove the parameter
unset($queryParams['page']);
and rebuild the url
$queryString = http_build_query($queryParams);
$url = $parts['path'] . '?' . $queryString;
There are many roads that lead to Rome. I'd do it with a RegEx:
$myString = 'index.php?properties&status=av&page=1';
$myNewString = preg_replace("/\&[a-z0-9]+=[0-9]+$/i","",$myString);
if you only want the &page=1-type parameters, the last line would be
$myNewString = preg_replace("/\&page=[0-9]+/i","",$myString);
if you also want to get rid of the possibility that page is the only or first parameter:
$myNewString = preg_replace("/[\&]*page=[0-9]+/i","",$myString);
Thank you guys but i think i have found the better solution, #KingCrunch had suggested a solution i extended and converted it into function. the below function can possibly remove or unset any URI variable without any regex hacks being used. i am posting it as it might help someone.
function unset_uri_var($variable, $uri) {
$parseUri = parse_url($uri);
$arrayUri = array();
parse_str($parseUri['query'], $arrayUri);
unset($arrayUri[$variable]);
$newUri = http_build_query($arrayUri);
$newUri = $parseUri['path'].'?'.$newUri;
return $newUri;
}
now consider the following uri
index.php?properties&status=av&page=1
//To remove properties variable
$url = unset_uri_var('properties', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?page=1&status=av
//To remove page variable
$url = unset_uri_var('page', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?properties=&status=av
hope this helps someone. and thank you #KingKrunch for your solution :)
$pos = strrpos($_SERVER['REQUEST_URI'], '&');
$url = substr($_SERVER['REQUEST_URI'], 0, $pos - 1);
Documentation for strrpos.
Regex that works on every possible situation: /(&|(?<=\?))page=.*?(?=&|$)/. Here's example code:
$regex = '/(&|(?<=\?))page=.*?(?=&|$)/';
$urls = array(
'index.php?properties&status=av&page=1',
'index.php?properties&page=1&status=av',
'index.php?page=1',
);
foreach($urls as $url) {
echo preg_replace($regex, '', $url), "\n";
}
Output:
index.php?properties&status=av
index.php?properties&status=av
index.php?
Regex explanation:
(&|(?<=\?)) -- either match a & or a ?, but if it's a ?, don't put it in the match and just ignore it (you don't want urls like index.php&status=av)
page=.*? -- matches page=[...]
(?=&|$) -- look for a & or the end of the string ($), but don't include them for the replacement (this group helps the previous one find out exactly where to stop matching)
You could use a RegEx (as Chris suggests) but it's not the most efficient solution (lots of overhead using that engine... it's easy to do with some string parsing:
<?php
//$url="http://localhost/index.php?properties&status=av&page=1";
$base=basename($_SERVER['REQUEST_URI']);
echo "Basename yields: $base<br />";
//Find the last ampersand
$lastAmp=strrpos($base,"&");
//Filter, catch no ampersands found
$removeLast=($lastAmp===false?$base:substr($base,0,$lastAmp));
echo "Without Last Parameter: $removeLast<br />";
?>
The trick is, can you guarantee that $page will be stuck on the end? If it is - great, if it isn't... what you asked for may not always solve the problem.
Hey there!
I have a simple question that I am struggling with, hope you guys can have a look.
I have a input field where users would put in YouTube links and your typical single page works fine, for example:
youtube.com/watch?v=c3sBBRxDAqk
this watch?v=11characters works fine
but if the users inputs anything other than the above example, such as:
youtube.com/watch?v=tC0E1id4raw&feature=topvideos
//or
youtube.com/watch?v=smETLCCPTVo&feature=aso
is there a way to take the 2 above urls and remove any characters after the watch?v=11characters?
so in essence, turn this
$url = "youtube.com/watch?v=tC0E1id4raw&feature=topvideos"
into
youtube.com/watch?v=tC0E1id4raw removing & and onwards
I had to remove the http bit due to spam prevention
is there a simple way to do this?
$url = "youtube.com/watch?v=tC0E1id4raw&feature=topvideos";
list($keep, $chuck) = explode('&', $url);
echo $keep;
One way to do this is using explode:
$url = "youtube.com/watch?v=tC0E1id4raw&feature=topvideos";
$newurl = explode("&", $url);
Everything before the "&" will be in $newurl[0], and everything after it will be in $newurl[1].
No need for regex:
$parts = parse_url($url);
$params = array();
parse_str($parts['query'], $params);
If you have PECL pecl_http installed:
$url = http_build_url($url,
array('query' => 'v='. $params['v']),
HTTP_URL_REPLACE | HTTP_URL_STRIP_FRAGMENT);
Or without pecl_http:
$url = $parts['scheme'] . $parts['host'] . $parts['path'] . '?v=' . $params['v'];
This is more robust against changes of the order of the query parameters.
Reference: parse_url, parse_str, http_build_url