Replace a part of a url with php - php

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

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 two same and random characters following each other in string - PHP

Need to remove random aa/ or bb/ to zz/ letters (with slash) to get /logo/picture.png
$url = "/logo/aa/picture.png";
$url = "/logo/bb/picture.png";
$url = "/logo/cc/picture.png";
This is an alternative which doesn't care what's contained in that url part or what lengths url parts have:
$urlParts = explode('/', $url);
array_splice($urlParts, count($urlParts) - 2, 1);
$url = implode('/', $urlParts);
If the $url is always of the form you provided you could do:
$str1 = substr($url,0,5);
$str2 = substr($url,8,strlen($url));
$url = $str1.$str2;
if it's not always of the same form you could determine the substrings indexes programmatically, maybe using strpos function. More detail here
Luca Angioloni solution is correct but this is more stable:
$url preg_replace("/\/[a-z]{2}\//", "/", $url);
This will work even on url like: /img/xz/picture.png but if you have an url like this /ig/aa/picture.png this will remove /ig and not /aa

Remove characters from end of URL

Say I have a URL with something like this:
http://website.com/website/webpage/?message=newexpense
I have the following code to try and get the the URL before the question mark:
$post_url = $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$link_before_question_mark = explode('?', $actual_link);
$add_income_url = $link_before_question_mark[0];
In this example I would get the following URL:
http://website.com/website/webpage/
I'd like to remove the webpage portion of this so the URL is:
http://website.com/website/
How can I do this?
Use parse_url This way you have all components.
$url = 'http://website.com/website/webpage/?message=newexpense';
$pUrl = parse_url( $url);
echo $pUrl['scheme'] . '://' . $pUrl['host'] . $pUrl['path'];
You can do a similar trick using explode. Then pop the parts you don't need and implode the url back together. If you are sure that the part after '?' never contains a '/', you can replace your code with this one. If you're not sure, you should first remove the part after '/' and then run this code to remove the last part of the path.
<?php
$url = 'http://website.com/website/webpage/?message=newexpense';
$parts = explode('/', $url);
// Remove the last part from the array
$lastpart = array_pop($parts);
// If the last part is empty, or the last part starts with a '?'
// this means there was a '/' at the end of the url, so we
// need to pop another part.
if ($lastpart == '' or substr($lastpart, 0, 1) == '?')
array_pop($parts);
$url = implode('/', $parts);
var_dump($url);
I'd probably use dirname; it's specifically designed to strip the last stuff after a "/"...
$url = "http://website.com/website/webpage/?message=newexpense";
echo dirname(dirname($url))."/"; // "http://website.com/website/"
(As it says in the documentation, "dirname() operates naively on the input string, and is not aware of the actual filesystem...", so it's quite safe to use for this kind of purpose.)
Try it with explode
<?php
$actual_link = "http://website.com/website/webpage/?message=newexpense]";
$link_before_question_mark = explode('?', $actual_link);
$add_income_url = $link_before_question_mark[0];
$split=explode('/', $add_income_url);
echo $split[0]."//".$split[2]."/".$split[3]."/";
?>
Even better is...
<?php
$actual_link = "http://website.com/website/webpage/?message=newexpense]";
$split=explode('/', $actual_link);
echo $split[0]."//".$split[2]."/".$split[3]."/";
?>

get url after http:// from complete url string using php

i am storing url string in database like this,
'http://www.domain.com'
how can i display above string like
'www.domain.com'
I need regular expression in first hand
with parse_url() you can split a url into it's parts and get the ones you want to. in your case (looking for the host), it would be:
$url = 'http://www.domain.com';
$parts = parse_url($url);
$result = $parts['host'];
this has a big advantage over the other posted solutions: it's ready to go with https-urls, urls with get-parameters and/or url's including htaccess-authentication paramneters without having to change the code.
simply you can use
$url = 'http://www.domain.com';
str_replace('http://', '', $url);
it will return exactly www.domain.com
A general solution for modifying strings without parsing the URL (i.e. you should learn to be able to do something like this yourself):
if (stripos($url, 'http://', 0) == 0)
$url = substr($url, 7);
You also could easily add another check for a https:// prefix or whatever else:
if (stripos($url, 'https://', 0) == 0)
$url = substr($url, 8);
With a regular expression, albeit completely unnecessary as there is nothing that requires one, you could to it like this:
$url = preg_replace('/^http:\\/\\//', '', $url);
Or with direct support for https:
$url = preg_replace('/^https?:\\/\\//', '', $url);
You can use something like below:
<?php
str_replace('http://', '', $url);
Edit:
Since you insist on regex solution, here's one that takes care of http and https in one
echo preg_replace( '/^(htt|ht|tt)p\:?\/\//i', '', $url);
echo substr('http://www.domain.com',7);
if (substr('http://www.domain.com',7) == 'http://' or substr('https://www.domain.com',8) == 'https://')

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

Categories