PHP get hash after question mark - php

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);

Related

Using preg_replace on url variables

I have some very long URL variables. Here is one example.
http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Ultimately it would be nice if I could find a way to use preg_replace to simply change one variable even if in the middle of the string for instance in the string above change print=no to 'print=yes for example.
I will however settle for a preg_replace pattern match that allows me to delete ?image=XYZ_1555025022.jpg. as this is a variable the name could be anything. It will always have "?image" " at the start and end with "&"
I think one of the problems I have run into is that preg_match seems to have issues on strings with "=" contained in them .
I am completely lost here in this and all those characters make may head spin. Maybe someone can give some guidance please?
Here's a demo of how you can do some of things you want using explode, parse_str and http_build_query:
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
// split on first ?
list($path, $query_string) = explode('?', $url, 2);
// parse the query string
parse_str($query_string, $params);
// delete image param
unset($params['image']);
// change the print param
$params['print'] = 'yes';
// rebuild the query
$query_string = http_build_query($params);
// reassemble the URL
$url = $path . '?' . $query_string;
echo $url;
Output:
http://localhost/index.php?mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=yes&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Demo on 3v4l.org
You can use str_replace() or preg_replace() to get your job done, but parse_url() with parse_str() will give you more controls to modify any parameters easily by array index. Finally use http_build_query() to make your final url after modification.
<?php
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo "BEFORE".PHP_EOL;
print_r($query);
$query['print'] = 'yes';
echo "AFTER".PHP_EOL;
print_r($query);
?>
DEMO: https://3v4l.org/npGij

isolate the number exists at the end of the URI php

I have the following URI:
/belt/belts/fk/product/40P35871
And I want to retrieve the last content after the last /.
In this case is 40P35871.
How can I do this?
How about explode?
$elements = explode('/', $input);
$productId = end($elements);
Here's a different solution entirely. (and the simplest!)
Using basename
$var = "/belt/belts/fk/product/40P35871";
echo basename($var);
Output:
40P35871
You don't need regex for something simple like that. Consider using strrchr, documentation here
$lastcontent = substr(strrchr($uri, "/"), 1);
Considering this special case of $uri being a path, the best answer would be the one provided by Chtulhu.
basename will return the last part of a path, documentation here
$lastcontent = basename($uri);
Just like this
$str = '/belt/belts/fk/product/40P35871';
$arr = explode('/', $str);
$var = array_pop($arr);
var_dump($var);
or
$var = substr($str, strrpos($str,'/') + 1);
Try this
$result = preg_replace('%(/(?:[^/]+?/)+)([^/]+)\b%', '$2', $subject);
use this:
echo preg_replace('/[a-z0-9]$/i', '$1', $url);
this will give you the last position
note: but on this url only, query strings make this useless and use need to parse the url for the same first for this to work
Don't use regex. In this case you can act as the follow
myUrl = $_SERVER[REQUEST_URL];
$number = substr(strrpos(myUri,'/')+1);
You don't need regex.
Find the last content and get it using substr():
$lastcontent = substr(strrchr($uri, "/"), 1);

Replace string using php preg_replace

Hi all i know preg_replace can be used for formatting string but i need help in that concerned area my url will be like this
http://www.example.com/index.php/
also remove the http,https,ftp....sites also
what i want is to get
result as
example.com/index.php
echo preg_replace("~(([a-z]*[:](//))|(www.))~", '', "ftp://www.example.com");
$url = 'http://www.example.com/index.php/';
$strpos = strpos($url,'.');
$output = substr($url,$strpos+1);
$parts=parse_url($url);
unset($parts['scheme']);
//echo http_build_url($parts);
echo implode("",$parts);
EDIT
To use http_build_url you needs pecl_http you can use implode as alternate
Something like this
$url = "http://www.example.com/index.php";
$parts = parse_url($url);
unset($parts['scheme']);
echo preg_replace('/^((ww)[a-z\d][\x2E])/i', '', join('', $parts));
Output
example.com/index.php
Example #2
$url = "http://ww3.nysif.com/Workers_Compensation.aspx";
Output
nysif.com/Workers_Compensation.aspx

Remove URL regardless of format

Having a brain freeze...
Have a URL which may be in any of the formats :
http://url.com/stuff
url.com/somestuff
www.url.com/otherstuff
https://www.url.com/morestuff
You get the picture.
How do I remove the .com part to leave just the various 'stuff' parts ? For example, the above would end up :
stuff
somestuff
otherstuff
morestuff
You could achieve that using the following code:
$com_pos = strpos($url, '.com/');
$stuff_part = substr($url, $com_pos + 5);
Click here to see the working code.
This should do the trick for you!
<?php
$url = "http://url.com/stuff";
$querystring = preg_replace('#^(https|http)?(://)?(www.)?([a-zA-Z0-9-]+)\.[a-zA-Z]{2,6}/#', "", $url);
echo $querystring;
I submitted this answer because I'm not very fond of solutions using explode() to handle this. Maybe your query string contains more slashes so, you'd have to write exceptions for those cases.
You can use explode to make an array, then get the last element from the array.
$str = 'http://url.com/stuff';
$arr = explode('/', $str);
echo end($arr); // 'stuff'
$path = parse_url('http://url.com/stuff', PHP_URL_PATH);
If you leave the second parameter unspecified you can return an array including the domain etc.
Use explode function to divide the string.
<?php
$url = "http://url.com/stuff";
$stuff = explode("/", $url);
echo $stuff[sizeof($stuff) - 1];
?>
I used sizeof to access to last element.
preg_replace("/^(https?:\/\/)?[^\/]+/" ,"", $url);

PHP url question

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();

Categories