PHP use str_replace, substr and strpos all together - php

What I am trying to do is to convert url of a video on youtube/vimeo return a new url that can be embed into an iframe and automate video embed codes.
This is working like a charm.
$url = "http://vimeo.com/29431603";
$orj_value = array("watch?v=", "http://vimeo.com/");
$new_value = array("embed/", "http://player.vimeo.com/video/");
$url = str_replace($orj_value, $new_value, $url);
echo $url;
You know, youtube ads an ugly string too into url that starts with &, so when i include
$url = substr($url, 0, strpos($url, "&"));
before
echo $url;
it strips out the unwanted part of youtube url. But then, vimeo code which has no & inside just does not return anything. Seems after adding new line, code wants to see a & inside the url; otherwise to echo $url var displays blank screen.
2- For dailymotion, i need to strip out everything after first _
How should i edit the line below in order to include support of dailymotion too?
$url = substr($url, 0, strpos($url, "&"));
Thanks in advance to anyone going to answer :)

If strpos() can't find the character you search for it will return false, which could confuse substr().
Try something like this:
$url = strpos($url, "&") ? substr($url, 0, strpos($url, "&")) : $url;
As for your comment:
if(strpos($url, "&")) {
$url = substr($url, 0, strpos($url, "&"));
} else if(strpos($url, "_")) {
$url = substr($url, 0, strpos($url, "_"));
}
There are more elegant ways to do it (ex. REGEX) but this will do. Note that & or _ can't be the first character in string if you want to allow this add !== false to the condition.

Related

How to follow a URL redirect to the final location?

How can I get the final destination URL for an Airbnb short-link URL in PHP? (e.g. https://abnb.me/Vt3MA7vVyM)
Using Redirect Detective, I can see that the link gets redirected three times:
file_get_contents() follows the redirections defined in the HTTP response. But, there is a redirection in JavaScript using window.top.location. So, you can parse it using strpos() and a simple preg_match():
$url = 'https://abnb.me/Vt3MA7vVyM';
$ret = file_get_contents($url);
$pos = strpos($ret, 'window.top.location');
if ($pos !== false) {
$str = substr($ret, $pos);
$str = preg_match('~validate\("([^"]*)~', $str, $matches);
echo html_entity_decode($matches[1]);
}
Output:
https://airbnb.com/rooms/2110908?=&s=41&ref_device_id=43fb193006d0cb8848f689aec67ba15ae5c48471&user_id=10758532&_branch_match_id=519823851281523702

How to pregmatch youtube url with the youtube short url and get videoids from them php

Hi am trying to pregmatch youtube urls and youtube shorten url and get video ids from am able to pregmatch the youtube url but unable to pregmatch short url
Here is my code..
if (preg_match('#^(?:https://(?:www\\.)?youtube.com/)(watch\\?v=|v/)([a-zA-Z0-9_]*)#', $video_id, $match))
where videoid= https://www.youtube.com/watch?v=Xt4S-Ot0Jcs
How can I pregmatch short url like https://youtu.be/Xt4S-Ot0Jcs how can I get the videoids from both using php
You can try with a simpler regex if you just want to get the videoId :
if (preg_match('#(youtube\.com/watch\?v=|youtu\.be/)([a-zA-Z0-9_]*)#', $video_id, $match))
public function get_id($url)
{
$ytshorturl = 'youtu.be/';
$ytlongurl = 'www.youtube.com/watch?v=';
if (strpos($url, $ytshorturl) !== false) {
$url = str_replace($ytshorturl, $ytlongurl, $url);
}
$components = parse_url($url);
parse_str($components['query'], $results);
return $results['v'];
}
$url = "https://youtu.be/oeg192rQ1xE"; //sample url
echo "Id is : ". get_id($url);

Removing anchor (#hash) from URL

Is there any reliable way in PHP to clean a URL of anchor tags?
So input:
http://site.com/some/#anchor
Outputs:
http://site.com/some/
Using strstr()
$url = strstr($url, '#', true);
Using strtok()
Shorter way, using strtok:
$url = strtok($url, "#");
Using explode()
Alternative way to separate the url from the hash:
list ($url, $hash) = explode('#', $url, 2);
If you don't want the $hash at all, you can omit it in list:
list ($url) = explode('#', $url);
With PHP version >= 5.4 you don't even need to use list:
$url = explode('#', $url)[0];
Using preg_replace()
Obligatory regex solution:
$url = preg_replace('/#.*/', '', $url);
Using Purl
Purl is neat URL manipulation library:
$url = \Purl\Url::parse($url)->set('fragment', '')->getUrl();
There is also one other option with parse_url();
$str = 'http://site.com/some/#anchor';
$arr = parse_url($str);
echo $arr['scheme'].'://'.$arr['host'].$arr['path'];
Output:
http://site.com/some/
Alternative way
$url = 'http://site.com/some/#anchor';
echo str_replace('#'.parse_url($url,PHP_URL_FRAGMENT),'',$url);
Using parse_url():
function removeURLFragment($pstr_urlAddress = '') {
$larr_urlAddress = parse_url ( $pstr_urlAddress );
return $larr_urlAddress['scheme'].'://'.(isset($larr_urlAddress['user']) ? $larr_urlAddress['user'].':'.''.$larr_urlAddress['pass'].'#' : '').$larr_urlAddress['host'].(isset($larr_urlAddress['port']) ? ':'.$larr_urlAddress['port'] : '').$larr_urlAddress['path'].(isset($larr_urlAddress['query']) ? '?'.$larr_urlAddress['query'] : '');
}

Converting Rackspace Cloud Files CDN URLs from HTTP to HTTPS

I have a series of Rackspace Cloud Files CDN URLs stored which reference an HTTP address and I would like to convert them to the HTTPS equivalent.
Rackspace Cloud Files CDN URLs are in the following format:
http://c186397.r97.cf1.rackcdn.com/CloudFiles Akamai.pdf
And the SSL equivalent for this URL would be:
https://c186397.ssl.cf1.rackcdn.com/CloudFiles Akamai.pdf
The changes to the URL are (source):
HTTP becomes HTTPS
The second URI segment ('r97' in this example) becomes 'ssl'
The 'r00' part seems to vary in length (as some are 'r6' etc.) so I'm having trouble converting these URLs to HTTPS. Here's the code I have so far:
function rackspace_cloud_http_to_https($url)
{
//Replace the HTTP part with HTTPS
$url = str_replace("http", "https", $url, $count = 1);
//Get the position of the .r00 segment
$pos = strpos($url, '.r');
if ($pos === FALSE)
{
//Not present in the URL
return FALSE;
}
//Get the .r00 part to replace
$replace = substr($url, $pos, 4);
//Replace it with .ssl
$url = str_replace($replace, ".ssl", $url, $count = 1);
return $url;
}
This however does not work for URLs where the second segment is of a different length.
Any thoughts appreciated.
I know this is old, but if you are using this library: https://github.com/rackspace/php-opencloud you can use the getPublicUrl() method on the object, you just need to use the following namespace
use OpenCloud\ObjectStore\Constants as Constant;
// Code logic to upload file
$https_file_url = $response->getPublicUrl(Constant\UrlType::SSL);
Try this:
function rackspace_cloud_http_to_https($url)
{
$urlparts = explode('.', $url);
// check for presence of 'r' segment
if (preg_match('/r\d+/', $urlparts[1]))
{
// replace appropriate segments of url
$urlparts[0] = str_replace("http", "https", $urlparts[0]);
$urlparts[1] = 'ssl';
// put url back together
$url = implode('.', $urlparts);
return $url;
}
else
{
return false;
}
}

How to trim down a URL using regex in PHP?

I am struggling to finish this regex code in PHP. I want to trim down the following url which is held in variable $text so that it goes from:
http://www.site.net/showthread.php?tid=324&pid=...
to:
showthread.php?tid=324
Thank you kindly!
Why use a regex? The parse_url method should give you all you want: http://php.net/manual/en/function.parse-url.php
Edit: working example
$someurl = 'http://www.site.net/showthread.php?tid=324&pid=...';
$urlParts = parse_url($someurl, PHP_URL_PATH | PHP_URL_QUERY);
$params = parse_str($urlParts['query']);
unset($params['pid']);
$queryString = http_build_query($params);
$newUrl = $urlParts['path'] . '?' . $queryString;
Since $urlParts['path'] start with a / and you didn't want that, you could even use
$newUrl = substr($newUrl, 1);
and be done :) Does that help at all?
This should do it:
$url = 'http://www.site.net/showthread.php?tid=324&pid=...';
$pattern = "/showthread.php\?tid=[0-9]+/";
if (preg_match($pattern, $url, $match))
print_r($match);

Categories