user543468
user543468

Reputation: 3

Replace a part of a url with 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?

Upvotes: 0

Views: 937

Answers (3)

Felix Kling
Felix Kling

Reputation: 816580

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

Upvotes: 0

JohnK813
JohnK813

Reputation: 1124

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].

Upvotes: 0

labue
labue

Reputation: 2623

$url = "youtube.com/watch?v=tC0E1id4raw&feature=topvideos";

list($keep, $chuck) = explode('&', $url);

echo $keep;

Upvotes: 4

Related Questions