PHP Function to convert URL - php

I'm new to php. I really need your help to write a function to convert below URL
From orginal URL: http://www.domain.com/blahblah/**ID**/**FileName**.html
To new URL http://statics.domain.com/download/**ID**/**Filename**.mp4
I want to get ID and Filename in the new URL. Can anyone help me to do with this?

A dirty way which work :
$url = "http://www.domain.com/blahblah/ID/FileName.html";
$replace = array("http://www.domain.com/blahblah/", ".html");
$by = array("http://statics.domain.com/download/", ".mp4");
$newurl = str_replace($replace, $by, $url);
It's basicaly replace what you want by...what you want. But nothing more, and I'm pretty sure a better answer is possible technicaly-writing. ;)

A hack way is to explode() the string by / and take last two element of array. Second last element would be an ID where as last element would be a filename.
You will need to perform substr() on filename to remove last .html characters from string.
This is how you do it.
<?php
$url="http://www.domain.com/blahblah/ID/FileName.html";
$parts=explode("/",$url);
$totalparts=sizeof($parts);
$id=$parts[$totalparts-2];
$filename=substr($parts[$totalparts-1], 0, -5);
Demo: https://eval.in/659950

Solved. This is simple and works.
function converturl($url){
if(preg_match('/.*domain.com\/.*\/(.*?)\/(.*).html/is', $url, $id)){
$newurl = 'http://static.domain.com/download/'.$id[1].'/'.$id[2].'.mp4';
}else{
$newurl = 'URL is not support';
}
return $newurl;
}

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

Function to remove GET variable with php

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.

Categories