Get part of URL in PHP is not completely working - php

I've this code here:
$url = 'https://www.my-page.de/account/show/4913';
echo substr( $url, strrpos( $url, '/' ) + 1 );
This returns me the needed id:
4913
Now the problem begins. In some cases the URL looks like this:
$url = 'https://www.my-page.de/account/show/4913/';
$url = 'https://www.my-page.de/account/show/4913/?conversationId=xxx';
This means that my code don't works anymore. So is there any way to be 100 % sure that I always get my ID from the URL? The ID is always at the same position from the beginning on but the end can be different.
Update
When I've this code here I'm getting not the last part anymore. Any idea why and how to fix this?:
$url = 'https://my-page.de/account/show/4913/';
$id = basename( dirname( $url ) );
I just want to be sure that it works in every situation. In this case the selected part is:
show

You could use functions that are meant for directories and/or URLs:
echo basename(dirname($url));
//or
echo basename(pathinfo($url, PATHINFO_DIRNAME));
//or
echo basename(parse_url($url, PHP_URL_PATH));
The last one may return the filename if you had https://www.my-page.de/account/show/4913/index.php so you would want to use:
echo basename(dirname(parse_url($url, PHP_URL_PATH)));
Lot's of possibilities depending on what you need. The point is that there are specific functions for working with directories, filenames and URLs so that you don't have to treat them as just strings that have no meaning but unlimited possibilities..
Filesystem Functions
URL Functions

Just use explode() to turn it into an array, then get the 5th item to get the id:
<?php
$url = 'https://www.my-page.de/account/show/4913/?conversationId=xxx&trey=trey';
$arr = explode('/', $url);
$id = $arr[5];
echo '<pre>'. print_r($id, 1) .'</pre>';
then it doesn't matter how many query params there are, they'll always be last
refs:
https://www.php.net/manual/en/function.explode.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

Remove only 3 characters after a specific string

Hi I have this string for example
http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/it/clients/
I want to remove only 3 characters after bbbb-bbbbbbbbbb-2/, so basically I want to remove the it/ part (This it/ part may not always be it but it can be es/ or en/ or different languages always 2 characters )
The following will work provided the the URL structure doesn't change. I assume you're wanting to remove the language part of the URL.
<?php
$url = "http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/it/clients/";
$parsedURL = parse_url($url);
$path = explode('/', $parsedURL['path']);
unset($path[2]);
$url = "{$parsedURL['scheme']}://{$parsedURL['host']}";
$url .= implode('/', $path);
var_dump($url);
// string(47) "http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/clients/"
You can use regex to selecting target part of string and run it in preg_replace().
$url = "http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/it/clients/";
echo preg_replace("#(.*)\w{2}/([^/]+/)$#", "$1$2", $url);
See result of code in demo
Define your languages in an array. If a language is not defined in the array URL will be the same.
$mLanguages = ["en","it","bg","gr"];
$mURL = "http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/it/clients/";
$mURL = removeLanguageFromURL($mURL, $mLanguages);
echo $mURL; // Output http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/clients/
function removeLanguageFromUrl($mURL, $mLanguages){
foreach($mLanguages as $language){ // Search languages
if(strpos($mURL, $language) !== false) // If language is found in url remove it
$mURL = str_replace('/' . $language,'', $mURL);
}
return $mURL;
}

How to get part from URL

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

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