I am currently writing a webapp in which some pages are heavily reliant on being able to pull the correct youtube video in - and play it. The youtube URLS are supplied by the users and for this reason will generally come in with variants one of them may look like this:
http://www.youtube.com/watch?v=y40ND8kXDlg
while the other may look like this:
http://www.youtube.com/watch/v/y40ND8kXDlg
Currently I am able to pull the ID from the latter using the code below:
function get_youtube_video_id($video_id)
{
// Did we get a URL?
if ( FALSE !== filter_var( $video_id, FILTER_VALIDATE_URL ) )
{
// http://www.youtube.com/v/abcxyz123
if ( FALSE !== strpos( $video_id, '/v/' ) )
{
list( , $video_id ) = explode( '/v/', $video_id );
}
// http://www.youtube.com/watch?v=abcxyz123
else
{
$video_query = parse_url( $video_id, PHP_URL_QUERY );
parse_str( $video_query, $video_params );
$video_id = $video_params['v'];
}
}
return $video_id;
}
How can I deal with URLS that use the ?v version rather than the /v/ version?
Like this:
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = explode("?v=", $link);
$video_id = $video_id[1];
Here is universal solution:
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0&lololo";
$video_id = explode("?v=", $link); // For videos like http://www.youtube.com/watch?v=...
if (empty($video_id[1]))
$video_id = explode("/v/", $link); // For videos like http://www.youtube.com/watch/v/..
$video_id = explode("&", $video_id[1]); // Deleting any other params
$video_id = $video_id[0];
Or just use this regex:
(\?v=|/v/)([-a-zA-Z0-9]+)
<?php
// Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)
// http://youtu.be/dQw4w9WgXcQ
// http://www.youtube.com/embed/dQw4w9WgXcQ
// http://www.youtube.com/watch?v=dQw4w9WgXcQ
// http://www.youtube.com/?v=dQw4w9WgXcQ
// http://www.youtube.com/v/dQw4w9WgXcQ
// http://www.youtube.com/e/dQw4w9WgXcQ
// http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
// http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
// http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
// http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
// It also works on the youtube-nocookie.com URL with the same above options.
// It will also pull the ID from the URL in an embed code (both iframe and object tags)
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
?>
<?php
$your_url='https://www.youtube.com/embed/G_5-SqD2gtA';
function get_youtube_id_from_url($url)
{
if (stristr($url,'youtu.be/'))
{preg_match('/(https:|http:|)(\/\/www\.|\/\/|)(.*?)\/(.{11})/i', $url, $final_ID); return $final_ID[4]; }
else
{#preg_match('/(https:|http:|):(\/\/www\.|\/\/|)(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})/i', $url, $IDD); return $IDD[5]; }
}
echo get_youtube_id_from_url($your_url)
?>
Try:
function youtubeID($url){
$res = explode("v",$url);
if(isset($res[1])) {
$res1 = explode('&',$res[1]);
if(isset($res1[1])){
$res[1] = $res1[0];
}
$res1 = explode('#',$res[1]);
if(isset($res1[1])){
$res[1] = $res1[0];
}
}
return substr($res[1],1,12);
return false;
}
$url = "http://www.youtube.com/watch/v/y40ND8kXDlg";
echo youtubeID($url1);
Should work for both
Okay, this is a much better answer than my previous:
$link = 'http://www.youtube.com/watch?v=oHg5SJYRHA0&player=normal';
strtok($link, '?');
parse_str(strtok(''));
echo $v;
It's might be good to have this in a function to keep the new variables out of the global scope (unless you want them there, obviously).
This may not be in use still, but there might be other people looking for an answer, so, to get a YouTube ID from a URL.
P.S: This works for all types of URL, I've tested it;
Function getYouTubeID($URL){
$YouTubeCheck = preg_match('![?&]{1}v=([^&]+)!', $URL . '&', $Data);
If($YouTubeCheck){
$VideoID = $Data[1];
}
Return $VideoID;
}
Or just use the preg_match function itself;
If(preg_match('![?&]{1}v=([^&]+)!', $URL . '&', $Data)){
$VideoID = $Data[1];
}
Hope this helps someone :)!
Simplest method I know with YouTube.
function GetYouTubeId($url)
{
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
return $youtube_id;
}
$parts = explode('=', $link);
// $parts[1] will y40ND8kXDlg
This example works only if there's one '=' in the URL. Ever likely to be more?
i just would search for the last "/" or the last "=". After it you find always the video-id.
preg_match("#([\w\d\-]){11}#is", 'http://www.youtube.com/watch?v=y40ND8kXDlg', $matches);
echo $matches[1];
This is best way to get youtube vedio id , Or any field in url , but you must change index (V) from $ID_youtube['v'] to anything you want.
function getID_youtube($url)
{
parse_str(parse_url($url, PHP_URL_QUERY), $ID_youtube);
return $ID_youtube['v'];
}
<?php
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = str_replace('http://www.youtube.com/watch?v=', '', $link);
echo $video_id;
?>
Output:
oHg5SJYRHA0
Source
<?php
$url = "https://www.youtube.com/watch?v=uKW_FPsFiB8&feature=related";
parse_str( parse_url( $url, PHP_URL_QUERY ), $vid );
echo $vid['v'];
?>
Output: uKW_FPsFiB8
This will work for urls like https://www.youtube.com/watch?v=uKW_FPsFiB8&feature=related or https://www.youtube.com/watch?v=vzH8FH1HF3A&feature=relmfu or only https://www.youtube.com/watch?v=uKW_FPsFiB8
All YouTube video ids are 11 characters of length. I wrote Regex based it:
<?php
$url = "https://www.youtube.com/watch?v=gooWdc6kb80";
preg_match('/(?:\/|=)(.{11})(?:$|&|\?)/', $url, $matches);
echo $matches[1];
?>
It can match different YouTube video formats:
// http://youtu.be/dQw4w9WgXcQ
// http://www.youtube.com/embed/dQw4w9WgXcQ
// http://www.youtube.com/watch?v=dQw4w9WgXcQ
// http://www.youtube.com/?v=dQw4w9WgXcQ
// http://www.youtube.com/v/dQw4w9WgXcQ
// http://www.youtube.com/e/dQw4w9WgXcQ
// http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
// http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
// http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
// http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
// https://www.youtube.com/embed/dQw4w9WgXcQ?feature=oembed
// https://www.youtube.com/embed/dQw4w9WgXcQ?start=16&feature=oembed
Related
I am having below data.
Example 1
From : http://de.example.ch/biz/barbar-vintage-z%C3%BCrich
I want: /biz/barbar-vintage-z%C3%BCrich
And also if there is
http://www.example.ch/biz/barbar-vintage-z%C3%BCrich
Then
I also want
/biz/barbar-vintage-z%C3%BCrich
If you want to do it via regex then you can use:
$s = 'http://de.example.ch/biz/barbar-vintage-z%C3%BCrich';
echo preg_replace('~^https?://[^/]+~', '', $s);
//=> /biz/barbar-vintage-z%C3%BCrich
Otherwise as the comments says parse_url function also let you have this value.
function getRelativePath($url)
{
$matches = array();
if (preg_match('#^(http://|https://)([^./]+\.)+[a-z]{2,3}(/.*)$#', $url, $matches) {
return $matches[3];
} else {
return false;
}
}
You could use preg_match or preg_match_all
preg_match('~^https?://[^/]+\K.+~', $data, $matches);
DEMO
Just try this:
<?php
$url = 'http://de.example.ch/biz/barbar-vintage-z%C3%BCrich';
echo preg_replace('~^https?://[^/]+~', '', $url);
?>
Find a Youtube video link in PHP String and convert it into Embed Code?
Embed Code:
<iframe width="420" height="315" src="//www.youtube.com/embed/0GfCP5CWHO0" frameborder="0" allowfullscreen></iframe>
PHP Code / String:
<?php echo $post_details['description']; ?>
Youtube Link:
http://www.youtube.com/watch?v=0GfCP5CWHO0
Try this:
preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>",$post_details['description']);
There are two types of youtube link for one video:
Example:
$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';
This function handles both:
function getYoutubeEmbedUrl($url)
{
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))([a-zA-Z0-9_-]+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
The output of $link1 or $link2 would be the same :
$output1 = getYoutubeEmbedUrl($link1);
$output2 = getYoutubeEmbedUrl($link2);
// output for both: https://www.youtube.com/embed/NVcpJZJ60Ao
Now you can use the output in iframe!
A little enhancement of Joran's solution to handle also youtube short URL format:
function convertYoutube($string) {
return preg_replace(
"/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i",
"<iframe src=\"//www.youtube.com/embed/$2\" allowfullscreen></iframe>",
$string
);
}
You can test this function online here
A quick function for generating Embed url link of any of the FB/vimeo/youtube videos.
public function generateVideoEmbedUrl($url){
//This is a general function for generating an embed link of an FB/Vimeo/Youtube Video.
$finalUrl = '';
if(strpos($url, 'facebook.com/') !== false) {
//it is FB video
$finalUrl.='https://www.facebook.com/plugins/video.php?href='.rawurlencode($url).'&show_text=1&width=200';
}else if(strpos($url, 'vimeo.com/') !== false) {
//it is Vimeo video
$videoId = explode("vimeo.com/",$url)[1];
if(strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://player.vimeo.com/video/'.$videoId;
}else if(strpos($url, 'youtube.com/') !== false) {
//it is Youtube video
$videoId = explode("v=",$url)[1];
if(strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
}else if(strpos($url, 'youtu.be/') !== false){
//it is Youtube video
$videoId = explode("youtu.be/",$url)[1];
if(strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
}else{
//Enter valid video URL
}
return $finalUrl;
}
Example:
$link1 = getEmbedUrl('https://www.youtube.com/watch?v=BIjqw7zuEVE');
$link2 = getEmbedUrl('https://vimeo.com/356810502');
$link3 = getEmbedUrl('https://example.com/link/12345');
Function:
function getEmbedUrl($url) {
// function for generating an embed link
$finalUrl = '';
if (strpos($url, 'facebook.com/') !== false) {
// Facebook Video
$finalUrl.='https://www.facebook.com/plugins/video.php?href='.rawurlencode($url).'&show_text=1&width=200';
} else if(strpos($url, 'vimeo.com/') !== false) {
// Vimeo video
$videoId = isset(explode("vimeo.com/",$url)[1]) ? explode("vimeo.com/",$url)[1] : null;
if (strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://player.vimeo.com/video/'.$videoId;
} else if (strpos($url, 'youtube.com/') !== false) {
// Youtube video
$videoId = isset(explode("v=",$url)[1]) ? explode("v=",$url)[1] : null;
if (strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
} else if(strpos($url, 'youtu.be/') !== false) {
// Youtube video
$videoId = isset(explode("youtu.be/",$url)[1]) ? explode("youtu.be/",$url)[1] : null;
if (strpos($videoId, '&') !== false) {
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
} else if (strpos($url, 'dailymotion.com/') !== false) {
// Dailymotion Video
$videoId = isset(explode("dailymotion.com/",$url)[1]) ? explode("dailymotion.com/",$url)[1] : null;
if (strpos($videoId, '&') !== false) {
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.dailymotion.com/embed/'.$videoId;
} else{
$finalUrl.=$url;
}
return $finalUrl;
}
I know this is an old thread, but for anyone having this challenge and looking for assistance, I found a PHP Class on GitHub - Embera.
Basically an oembed library which converts YouTube URLs in any string into the associated iframe element. I'm using it, and will continue to use it everywhere!
I think a safe, super simple way to get the id
which is kinda bulletproof is to simply use the URL structure.
function getYoutubeEmbedUrl($url){
$urlParts = explode('/', $url);
$vidid = explode( '&', str_replace('watch?v=', '', end($urlParts) ) );
return 'https://www.youtube.com/embed/' . $vidid[0] ;
}
Below will work for all type of YouTube URLs.
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
<?php
$url = 'https://www.youtube.com/watch?v=u9-kU7gfuFA';
preg_match('/[\\?\\&]v=([^\\?\\&]+)/', $url, $matches);
$id = $matches[1];
$width = '800px';
$height = '450px'; ?>
<iframe id="ytplayer" type="text/html" width="<?php echo $width ?>" height="<?php echo $height ?>"
src="https://www.youtube.com/embed/<?php echo $id ?>?rel=0&showinfo=0&color=white&iv_load_policy=3"
frameborder="0" allowfullscreen></iframe>
Another simple alternative would be using parse_url and parse_str functions.
function getYoutubeEmbedUrl ($url) {
$parsedUrl = parse_url($url);
# extract query string
parse_str(#$parsedUrl['query'], $queryString);
$youtubeId = #$queryString['v'] ?? substr(#$parsedUrl['path'], 1);
return "https://youtube.com/embed/{$youtubeId}";
}
Lets say we have these two links:
$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';
getYoutubeEmbedUrl($link1); // https://youtube.com/embed/NVcpJZJ60Ao
getYoutubeEmbedUrl($link2); // https://youtube.com/embed/NVcpJZJ60Ao
Explanation
parse_url function will extract link into 4 components: scheme, host, path, and query (see docs).
parse_url($link1);
// output
[
"scheme" => "https",
"host" => "www.youtube.com",
"path" => "/watch",
"query" => "v=NVcpJZJ60Ao",
]
The output of $link2 would be:
parse_url($link2);
// output
[
"scheme" => "https",
"host" => "www.youtu.be",
"path" => "/NVcpJZJ60Ao",
]
And parse_str will convert query string into an array (see docs).
parse_str('v=NVcpJZJ60Ao', $output);
// value of variable $output
[
"v" => "NVcpJZJ60Ao",
]
Well, you need to filter out the youtube links first and put them into an array.
Next you need to find out the video id of the url which is very easy. Use this script:
function getIDfromURL() {
var video_url = document.getElementById('url').value;
var video_id = video_url.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if (ampersandPosition != -1) { video_id = video_id.substring(0, ampersandPosition); }
document.getElementById('url').value=video_id;
}
You can of course use a PHP function as well, but I just used JS here to get the id from the URL. Maybe that helped anyways ;)
With the video id you can embed the video ;)
If the string is from user input, or in any way unpredictable, then forget using RegEx...seriously. It will open a can of worms for you.
Instead, try to look into using a HTML parser to extract the URL's based on certain rules and selectors.
I mainly use ColdFsuion / Java and JSoup is amazing for this kind of thing, with a whole lot more ease and security too.
http://jsoup.org/
It seems, in PHP, you could use something like this:
http://code.google.com/p/phpquery/
I'd love to give a code sample, but I don't know PHP well enough. But give it a go.
Mikey.
Try this too:
$text = "is here the text to replace";
function replace_iframe($id_video) {
return '<iframe height="315" width="100%" src="https://www.youtube.com/embed/'.$id_video[1].'" frameborder="0" allowfullscreen></iframe>';
}
echo preg_replace_callback("/\s*[a-zA-Z\/\/:\.]*(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i", 'replace_iframe', $text);
Example:
http://www.dailymotion.com/video/x4xvnz_the-funny-crash-compilation_fun
How do I get x4xvnz?
You can use basename [docs] to get the last part of the URL and then strtok [docs] to get the ID (all characters up to the first _):
$id = strtok(basename($url), '_');
/video\/([^_]+)/
should do the trick. This grabs in the first capture all text after video/ up till the first _.
preg_match('#<object[^>]+>.+?http://www.dailymotion.com/swf/video/([A-Za-z0-9]+).+?</object>#s', $dailymotionurl, $matches);
// Dailymotion url
if(!isset($matches[1])) {
preg_match('#http://www.dailymotion.com/video/([A-Za-z0-9]+)#s', $dailymotionurl, $matches);
}
// Dailymotion iframe
if(!isset($matches[1])) {
preg_match('#http://www.dailymotion.com/embed/video/([A-Za-z0-9]+)#s', $dailymotionurl, $matches);
}
$id = $matches[1];
I use this:
function getDailyMotionId($url)
{
if (preg_match('!^.+dailymotion\.com/(video|hub)/([^_]+)[^#]*(#video=([^_&]+))?|(dai\.ly/([^_]+))!', $url, $m)) {
if (isset($m[6])) {
return $m[6];
}
if (isset($m[4])) {
return $m[4];
}
return $m[2];
}
return false;
}
It can handle various urls:
$dailymotion = [
'http://www.dailymotion.com/video/x2jvvep_coup-incroyable-pendant-un-match-de-ping-pong_tv',
'http://www.dailymotion.com/video/x2jvvep_rates-of-exchange-like-a-renegade_music',
'http://www.dailymotion.com/video/x2jvvep',
'http://www.dailymotion.com/hub/x2jvvep_Galatasaray',
'http://www.dailymotion.com/hub/x2jvvep_Galatasaray#video=x2jvvep',
'http://www.dailymotion.com/video/x2jvvep_hakan-yukur-klip_sport',
'http://dai.ly/x2jvvep',
];
Check out my github (https://github.com/lingtalfi/video-ids-and-thumbnails/blob/master/testvideo.php), I provide functions to get ids (and also thumbnails) from youtube, vimeo and dailymotion.
<?php
$output = parse_url("http://www.dailymotion.com/video/x4xvnz_the-funny-crash-compilation_fun");
// The part you want
$url= $output['path'];
$parts = explode('/',$url);
$parts = explode('_',$parts[2]);
echo $parts[0];
http://php.net/manual/en/function.parse-url.php
I have some links in a Powerpoint presentation, and for some reason, when those links get clicked, it adds a return parameter to the URL. Well, that return parameter is causing my Joomla site's MVC pattern to get bungled.
What's an efficient way to strip off this return parameter using PHP?
Example:
http://mydomain.example/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0
The safest "correct" method would be:
Parse the url into an array with parse_url()
Extract the query portion, decompose that into an array using parse_str()
Delete the query parameters you want by unset() them from the array
Rebuild the original url using http_build_query()
Quick and dirty is to use a string search/replace and/or regex to kill off the value.
In a different thread Justin suggests that the fastest way is to use strtok()
$url = strtok($url, '?');
See his full answer with speed tests as well here: https://stackoverflow.com/a/1251650/452515
This is to complement Marc B's answer with an example, while it may look quite long, it's a safe way to remove a parameter. In this example we remove page_number
<?php
$x = 'http://url.example/search/?location=london&page_number=1';
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['page_number']);
$string = http_build_query($params);
var_dump($string);
function removeParam($url, $param) {
$url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*$/', '', $url);
$url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*&/', '$1', $url);
return $url;
}
parse_str($queryString, $vars);
unset($vars['return']);
$queryString = http_build_query($vars);
parse_str parses a query string, http_build_query creates a query string.
Procedural Implementation of Marc B's Answer after refining Sergey Telshevsky's Answer.
function strip_param_from_url($url, $param)
{
$base_url = strtok($url, '?'); // Get the base URL
$parsed_url = parse_url($url); // Parse it
// Add missing {
if(array_key_exists('query',$parsed_url)) { // Only execute if there are parameters
$query = $parsed_url['query']; // Get the query string
parse_str($query, $parameters); // Convert Parameters into array
unset($parameters[$param]); // Delete the one you want
$new_query = http_build_query($parameters); // Rebuilt query string
$url =$base_url.'?'.$new_query; // Finally URL is ready
}
return $url;
}
// Usage
echo strip_param_from_url( 'http://url.example/search/?location=london&page_number=1', 'location' )
You could do a preg_replace like:
$new_url = preg_replace('/&?return=[^&]*/', '', $old_url);
Here is the actual code for what's described above as the "the safest 'correct' method"...
function reduce_query($uri = '') {
$kill_params = array('gclid');
$uri_array = parse_url($uri);
if (isset($uri_array['query'])) {
// Do the chopping.
$params = array();
foreach (explode('&', $uri_array['query']) as $param) {
$item = explode('=', $param);
if (!in_array($item[0], $kill_params)) {
$params[$item[0]] = isset($item[1]) ? $item[1] : '';
}
}
// Sort the parameter array to maximize cache hits.
ksort($params);
// Build new URL (no hosts, domains, or fragments involved).
$new_uri = '';
if ($uri_array['path']) {
$new_uri = $uri_array['path'];
}
if (count($params) > 0) {
// Wish there was a more elegant option.
$new_uri .= '?' . urldecode(http_build_query($params));
}
return $new_uri;
}
return $uri;
}
$_SERVER['REQUEST_URI'] = reduce_query($_SERVER['REQUEST_URI']);
However, since this will likely exist prior to the bootstrap of your application, you should probably put it into an anonymous function. Like this...
call_user_func(function($uri) {
$kill_params = array('gclid');
$uri_array = parse_url($uri);
if (isset($uri_array['query'])) {
// Do the chopping.
$params = array();
foreach (explode('&', $uri_array['query']) as $param) {
$item = explode('=', $param);
if (!in_array($item[0], $kill_params)) {
$params[$item[0]] = isset($item[1]) ? $item[1] : '';
}
}
// Sort the parameter array to maximize cache hits.
ksort($params);
// Build new URL (no hosts, domains, or fragments involved).
$new_uri = '';
if ($uri_array['path']) {
$new_uri = $uri_array['path'];
}
if (count($params) > 0) {
// Wish there was a more elegant option.
$new_uri .= '?' . urldecode(http_build_query($params));
}
// Update server variable.
$_SERVER['REQUEST_URI'] = $new_uri;
}
}, $_SERVER['REQUEST_URI']);
NOTE: Updated with urldecode() to avoid double encoding via http_build_query() function.
NOTE: Updated with ksort() to allow params with no value without an error.
This one of many ways, not tested, but should work.
$link = 'http://mydomain.example/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0';
$linkParts = explode('&return=', $link);
$link = $linkParts[0];
Wow, there are a lot of examples here. I am providing one that does some error handling. It rebuilds and returns the entire URL with the query-string-param-to-be-removed, removed. It also provides a bonus function that builds the current URL on the fly. Tested, works!
Credit to Mark B for the steps. This is a complete solution to tpow's "strip off this return parameter" original question -- might be handy for beginners, trying to avoid PHP gotchas. :-)
<?php
function currenturl_without_queryparam( $queryparamkey ) {
$current_url = current_url();
$parsed_url = parse_url( $current_url );
if( array_key_exists( 'query', $parsed_url )) {
$query_portion = $parsed_url['query'];
} else {
return $current_url;
}
parse_str( $query_portion, $query_array );
if( array_key_exists( $queryparamkey , $query_array ) ) {
unset( $query_array[$queryparamkey] );
$q = ( count( $query_array ) === 0 ) ? '' : '?';
return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . $q . http_build_query( $query_array );
} else {
return $current_url;
}
}
function current_url() {
$current_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
return $current_url;
}
echo currenturl_without_queryparam( 'key' );
?>
$var = preg_replace( "/return=[^&]+/", "", $var );
$var = preg_replace( "/&{2,}/", "&", $var );
Second line will just replace && to &
very simple
$link = "http://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0"
echo substr($link, 0, strpos($link, "return") - 1);
//output : http://example.com/index.php?id=115&Itemid=283
#MarcB mentioned that it is dirty to use regex to remove an url parameter. And yes it is, because it's not as easy as it looks:
$urls = array(
'example.com/?foo=bar',
'example.com/?bar=foo&foo=bar',
'example.com/?foo=bar&bar=foo',
);
echo 'Original' . PHP_EOL;
foreach ($urls as $url) {
echo $url . PHP_EOL;
}
echo PHP_EOL . '#AaronHathaway' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('#&?foo=[^&]*#', null, $url) . PHP_EOL;
}
echo PHP_EOL . '#SergeS' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace( "/&{2,}/", "&", preg_replace( "/foo=[^&]+/", "", $url)) . PHP_EOL;
}
echo PHP_EOL . '#Justin' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('/([?&])foo=[^&]+(&|$)/', '$1', $url) . PHP_EOL;
}
echo PHP_EOL . '#kraftb' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('/(&|\?)foo=[^&]*&/', '$1', preg_replace('/(&|\?)foo=[^&]*$/', '', $url)) . PHP_EOL;
}
echo PHP_EOL . 'My version' . PHP_EOL;
foreach ($urls as $url) {
echo str_replace('/&', '/?', preg_replace('#[&?]foo=[^&]*#', null, $url)) . PHP_EOL;
}
returns:
Original
example.com/?foo=bar
example.com/?bar=foo&foo=bar
example.com/?foo=bar&bar=foo
#AaronHathaway
example.com/?
example.com/?bar=foo
example.com/?&bar=foo
#SergeS
example.com/?
example.com/?bar=foo&
example.com/?&bar=foo
#Justin
example.com/?
example.com/?bar=foo&
example.com/?bar=foo
#kraftb
example.com/
example.com/?bar=foo
example.com/?bar=foo
My version
example.com/
example.com/?bar=foo
example.com/?bar=foo
As you can see only #kraftb posted a correct answer using regex and my version is a little bit smaller.
Remove Get Parameters From Current Page
<?php
$url_dir=$_SERVER['REQUEST_URI'];
$url_dir_no_get_param= explode("?",$url_dir)[0];
echo $_SERVER['HTTP_HOST'].$url_dir_no_get_param;
This should do it:
public function removeQueryParam(string $url, string $param): string
{
$parsedUrl = parse_url($url);
if (isset($parsedUrl[$param])) {
$baseUrl = strtok($url, '?');
parse_str(parse_url($url)['query'], $query);
unset($query[$param]);
return sprintf('%s?%s',
$baseUrl,
http_build_query($query)
);
}
return $url;
}
Simple solution that will work for every url
With this solution $url format or parameter position doesn't matter, as an example I added another parameter and anchor at the end of $url:
https://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0&bonus=test#test2
Here is the simple solution:
$url = 'https://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0&bonus=test#test2';
$url_query_stirng = parse_url($url, PHP_URL_QUERY);
parse_str( $url_query_stirng, $url_parsed_query );
unset($url_parsed_query['return']);
$url = str_replace( $url_query_stirng, http_build_query( $url_parsed_query ), $url );
echo $url;
Final result for $url string is:
https://example.com/index.php?id=115&Itemid=283&bonus=test#test2
Some of the examples posted are so extensive. This is what I use on my projects.
function removeQueryParameter($url, $param){
list($baseUrl, $urlQuery) = explode('?', $url, 2);
parse_str($urlQuery, $urlQueryArr);
unset($urlQueryArr[$param]);
if(count($urlQueryArr))
return $baseUrl.'?'.http_build_query($urlQueryArr);
else
return $baseUrl;
}
function remove_attribute($url,$attribute)
{
$url=explode('?',$url);
$new_parameters=false;
if(isset($url[1]))
{
$params=explode('&',$url[1]);
$new_parameters=ra($params,$attribute);
}
$construct_parameters=($new_parameters && $new_parameters!='' ) ? ('?'.$new_parameters):'';
return $new_url=$url[0].$construct_parameters;
}
function ra($params,$attr)
{ $attr=$attr.'=';
$new_params=array();
for($i=0;$i<count($params);$i++)
{
$pos=strpos($params[$i],$attr);
if($pos===false)
$new_params[]=$params[$i];
}
if(count($new_params)>0)
return implode('&',$new_params);
else
return false;
}
//just copy the above code and just call this function like this to get new url without particular parameter
echo remove_attribute($url,'delete_params'); // gives new url without that parameter
I know this is an old question but if you only want to remove one or few named url parameter you can use this function:
function RemoveGet_Regex($variable, $rewritten_url): string {
$rewritten_url = preg_replace("/(\?)$/", "", preg_replace("/\?&/", "?", preg_replace("/((?<=\?)|&){$variable}=[\w]*/i", "", $rewritten_url)));
return $rewritten_url;
}
function RemoveGet($name): void {
$rewritten_url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(is_array($name)) {
for($i = 0; $i < count($name); $i++) {
$rewritten_url = RemoveGet_Regex($name[$i], $rewritten_url);
$is_set[] = isset($_GET[$name[$i]]);
}
$array_filtered = array_filter($is_set);
if (!empty($array_filtered)) {
header("Location: ".$rewritten_url);
}
}
else {
$rewritten_url = RemoveGet_Regex($name, $rewritten_url);
if(isset($_GET[$name])) {
header("Location: ".$rewritten_url);
}
}
}
In the first function preg_replace("/((?<=\?)|&){$variable}=[\w]*/i", "", $rewritten_url) will remove the get parameter, and the others will tidy it up. The second function will then redirect.
RemoveGet("id"); will remove the id=whatever from the url. The function can also work with arrays. For your example,
Remove(array("id","Item","return"));
To strip any parameter from the url using PHP script you need to follow this script:
function getNewArray($array,$k){
$dataArray = $array;
unset($array[$k]);
$dataArray = $array;
return $dataArray;
}
function getFullURL(){
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}
$url = getFullURL();
$url_components = parse_url($url);
// Use parse_str() function to parse the
// string passed via URL
parse_str($url_components['query'], $params);
print_r($params);
<ul>
<?php foreach($params as $k=>$v){?>
<?php
$newArray = getNewArray($params,$k);
$parameters = http_build_query($newArray);
$newURL = $_SERVER['PHP_SELF']."?".$parameters;
?>
<li><?=$v;?> X
<?php }?>
</ul>
here is functions optimized for speed. But this functions DO NOT remove arrays like a[]=x&a[1]bb=y&a[2]=z by array name.
function removeQueryParam($query, $param)
{
$quoted_param = preg_quote($param, '/');
$pattern = "/(^$quoted_param=[^&]*&?)|(&$quoted_param=[^&]*)/";
return preg_replace($pattern, '', $query);
}
function removeQueryParams($query, array $params)
{
if ($params)
{
$pattern = '/';
foreach ($params as $param)
{
$quoted_param = preg_quote($param, '/');
$pattern .= "(^$quoted_param=[^&]*&?)|(&$quoted_param=[^&]*)|";
}
$pattern[-1] = '/';
return preg_replace($pattern, '', $query);
}
return $query;
}
<? if(isset($_GET['i'])){unset($_GET['i']); header('location:/');} ?>
This will remove the 'i' parameter from the URL. Change the 'i's to whatever you need.
I am wondering if there is a simple snippet which converts links of any kind:
http://www.cnn.com to http://www.cnn.com
cnn.com to cnn.com
www.cnn.com to www.cnn.com
abc#def.com to to mailto:abc#def.com
I do not want to use any PHP5 specific library.
Thank you for your time.
UPDATE I have updated the above text to what i want to convert it to. Please note that the href tag and the text are different for case 2 and 3.
UPDATE2 Hows does gmail chat do it? Theirs is pretty smart and works only for real domains names. e.g. a.ly works but a.cb does not work.
yes ,
http://www.gidforums.com/t-1816.html
<?php
/**
NAME : autolink()
VERSION : 1.0
AUTHOR : J de Silva
DESCRIPTION : returns VOID; handles converting
URLs into clickable links off a string.
TYPE : functions
======================================*/
function autolink( &$text, $target='_blank', $nofollow=true )
{
// grab anything that looks like a URL...
$urls = _autolink_find_URLS( $text );
if( !empty($urls) ) // i.e. there were some URLS found in the text
{
array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) );
$text = strtr( $text, $urls );
}
}
function _autolink_find_URLS( $text )
{
// build the patterns
$scheme = '(http:\/\/|https:\/\/)';
$www = 'www\.';
$ip = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
$subdomain = '[-a-z0-9_]+\.';
$name = '[a-z][-a-z0-9]+\.';
$tld = '[a-z]+(\.[a-z]{2,2})?';
$the_rest = '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';
$pattern = "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest";
$pattern = '/'.$pattern.'/is';
$c = preg_match_all( $pattern, $text, $m );
unset( $text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern );
if( $c )
{
return( array_flip($m[0]) );
}
return( array() );
}
function _autolink_create_html_tags( &$value, $key, $other=null )
{
$target = $nofollow = null;
if( is_array($other) )
{
$target = ( $other['target'] ? " target=\"$other[target]\"" : null );
// see: http://www.google.com/googleblog/2005/01/preventing-comment-spam.html
$nofollow = ( $other['nofollow'] ? ' rel="nofollow"' : null );
}
$value = "<a href=\"$key\"$target$nofollow>$key</a>";
}
?>
Try this out. (for links not email)
$newTweet = preg_replace('!http://([a-zA-Z0-9./-]+[a-zA-Z0-9/-])!i', '\\0', $tweet->text);
I know is 5 years late, however I needed a similar solution and the best answer I got was from the user - erwan-dupeux-maire
Answer
I write this function. It replaces all the links in a string. Links can be in the following formats :
www.example.com
http://example.com
https://example.com
example.fr
The second argument is the target for the link ('_blank', '_top'... can be set to false). Hope it helps...
public static function makeLinks($str, $target='_blank')
{
if ($target)
{
$target = ' target="'.$target.'"';
}
else
{
$target = '';
}
// find and replace link
$str = preg_replace('#((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)#', '<a href="$1" '.$target.'>$1</a>', $str);
// add "http://" if not set
$str = preg_replace('/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '<a href="http://$1" '.$target.'>', $str);
return $str;
}
Here's the email snippet:
$email = "abc#def.com";
$pos = strrpos($email, "#");
if (!$pos === false) {
// This is an email address!
$email .= "mailto:" . $email;
}
What exactly are you looking to do with the links? strip the www or http? or add http://www to any link if required?