How to get part from URL - php

Well sorry for the probably misleading title. Wasn't sure how to describe it better.
When accessing the status page I want to get the attached ID. But I don't want to use GET fields (wordpress makes /status?id=2134 to /status/?id=1234 - that's the only reason actually).
So this is my url
http://foo.bar.com/status/1234/
I want to get 1234
Okay fine. I could use something like $_SERVER["REQUEST_URI"] + trim() for example. Probably regex would be the key to get this job done since one could do something like /status/1234/foo/bar/baz/.. But I'm wondering if there is something builtin with PHP to get this part of the url.

Use the parse_url() function, and extract it:
$url = 'http://foo.bar.com/status/1234/';
$path = trim(parse_url($url, PHP_URL_PATH), '/');
$items = explode('/', $path);
$num = array_pop($items);
var_dump($num);
You can also use a regular expression, if that tickles your fancy:
$url = 'http://foo.bar.com/status/1234/';
$path = parse_url($url, PHP_URL_PATH);
preg_match('~/status/(?P<num>\d+)/?~', $path, $result);
$num = isset($result['num']) ? $result['num'] : null;
var_dump($num);

Try to parses a URL and returns an associative array containing any of the various components of the URL that are present using parse_url, explode it using explode and finally select status id using end
Try like this
$url = 'http://foo.bar.com/status/1234/';
$statusId = explode('/',trim(parse_url($url, PHP_URL_PATH), '/'));
print end($statusId);
Demo Ex http://ideone.com/34iDnh
trim- http://php.net/trim
explode-http://php.net/explode
parse_url-[1]: http://php.net/manual/en/function.parse-url.php

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

How to remove last part of url in PHP

$url = explode('/', $articleimage);
$articleurl = array_pop($url);
I have used the above method to get the last part of a URL.Its working.But I want to remove the last part from the URL and display the remaining part.Please help me.Here I am mentioning the example URL.
http://www.brightknowledge.org/knowledge-bank/media/studying-media/student-media/image_rhcol_thin
Try this:
$url = explode('/', 'http://www.brightknowledge.org/knowledge-bank/media/studying-media/student-media/image_rhcol_thin');
array_pop($url);
echo implode('/', $url);
There is no need to use explode, implode, and array_pop.
Just use dirname($path). It's a lot more efficient and cleaner code.
Use the following string manipulation from PHP
$url_without_last_part = substr($articleimage, 0, strrpos($articleimage, "/"));
For Laravel
dirname(url()->current())
In url()->current() -> you will get current URL.
In dirname -> You will get parent directory.
In Core PHP:
dirname($currentURL)
after the array_pop you can do
$url2=implode("/",$url)
to get the url in a string
Change this:
$articleurl = array_pop($url);
Into this:
$articleurl = end($url);
$articleurl will then hold the last array key.
Missed the part where you want to remove the value, you can use the function key() to get the key and then remove the value using that key
$array_key = key($articleurl);
unset(url[$array_key])
Pretty simple solution add in the end of your code
$url = implode('/', $url);
echo $url;
Notice that array_pop use reference argument passing so array will be modifed implode() function does the opposite to explode function and connects array elements by first argument(glue) and returns the string.
It looks like this may be what you are looking for. Instead of exploding and imploding, you can use the parsing functions which are designed to handle exactly this kind of URL manipulation.
$url = parse_url( $url_string );
$result =
$url['scheme']
. "://"
. $url['host']
. pathinfo($url['path'], PATHINFO_DIRNAME );
Here's the simple way to achieve
str_replace(basename($articleimage), '', $articleimage);
For the one-liners:
$url = implode('/', array_splice( explode('/', $articleimage), 0, -1 ) );
$url[''] and enter the appropriate number

Using rtrim in php for specific purpose

I am not much used to using rtrim and Reg expressions. So I wanted to get my doubt cleared about this:
Here is a url: http://imgur.com/r/pics/paoWS
I am trying to use rtrim function on this url to pick out only the 'paoWs' from the whole url.
Here is what i tried:
$yurl = 'http://imgur.com/r/pics/paoWS';
$video_id = parse_url($yurl, PHP_URL_PATH);
$yid=rtrim( $video_id, '/' );
And i am using '$yid' to hotlink the image from imgur. But What I get after trying this function is:
$yid= '/r/pics/paoWS'
How do I solve this?
rtrim is used for trimming down a string of certain characters or whitespace on the right-hand side. It certainly shouldn't be used for your purpose.
Assuming the URL structure will always be the same, you could just do something like this:
$yurl = 'http://imgur.com/r/pics/paoWS';
$video_id = parse_url($yurl, PHP_URL_PATH);
$parts = explode('/', $video_id)
$yid = end($parts);
You sould not use regular expressions (whitch are 'expensive') for a so 'simple' problem.
If you want to catch the last part of the URL, after the last slash, you can do :
$urlParts = explode('/', 'http://imgur.com/r/pics/paoWS');
$lastPart = end($urlParts);
rtim( strrchr('http://imgur.com/r/pics/paoWS' , '/') ); rtrim + strrchr
substr(strrchr('http://imgur.com/r/pics/paoWS', "/"), 1); substr + strrchr
rtrim() returns the filtered value, not the stripped characters. And your usage of it isn't proper too - it strips the passed characters from the right side. And you don't need parse_url() either.
Proper answers have been given already, but here's a faster alternative:
$yid = substr($yurl, strrpos($yurl, '/')+1);
Edit: And another one:
$yid = ltrim(strrchr($yurl, '/'), '/');

Function to shorten a specific string

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

php : Retrieving number in the URL

I have url in the following types
http://domain.com/1/index.php
http://domain.com/2/index.php
http://domain.com/3/index.php
http://domain.com/4/index.php
I need to retrieve only the number from the url .
for example,
when i visit http://domain.com/1/index.php , It must return 1.
Have a look at parse_url.
$url = parse_url('http://domain.com/1/index.php');
EDIT: Take a look at $_SERVER['REQUEST_URI'], to get the current URL. Use that instead of $url['path'].
Then you can split $url['path'] on /, and get the 1st element.
// use trim to remove the starting slash in 'path'
$path = explode('/', trim($url['path'], '/'));
$id = $path[0]; // 1
Given the information provided, this will do what you ask... it's not what I would call a robust solution:
$url = $_SERVER['PATH_INFO']; // e.g.: "http://domain.com/1/index.php";
$pieces = explode("/", $url);
$num = $pieces[3];
split the server path by forward slashes (explode('/', $_SERVER['REQUEST_PATH']);)
remove empty entry from the beginning
take the first element
make sure it is an integer (intval(), or a simple (int) cast).
No need to use regular expressions for this.
You use preg_match() to match the domain and get the 1st segment.
$domain = http://www.domain.com/1/test.html
preg_match("/http:\/\/.*\/(.*)\/.*/", "http://www.domain.com/1/test.html");
echo $matches[1]; // returns the number 1 in this example.

Categories