I am using a bit.ly shortener for my custom domain. It outputs http://shrt.dmn/abc123; however, I'd like it to just output shrt.dmn/abc123.
Here is my code.
//automatically create bit.ly url for wordpress widgets
function bitly()
{
//login information
$url = get_permalink(); //for wordpress permalink
$login = 'UserName'; //your bit.ly login
$apikey = 'API_KEY'; //add your bit.ly APIkey
$format = 'json'; //choose between json or xml
$version = '2.0.1';
//generate the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
//fetch url
$response = file_get_contents($bitly);
//for json formating
if(strtolower($format) == 'json')
{
$json = #json_decode($response,true);
echo $json['results'][$url]['shortUrl'];
}
else //for xml formatting
{
$xml = simplexml_load_string($response);
echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
As long as it is supposed to be url and if there is http:// - then this solution is the simplest possible:
$url = str_replace('http://', '', $url);
Change your following line:
echo $json['results'][$url]['shortUrl'];
for this one:
echo substr( $json['results'][$url]['shortUrl'], 7);
You want to do a preg_replace.
$variable = preg_replace( '/http:\/\//', '', $variable ); (this is untested, so you might also need to escape the : character ).
you can also achieve the same effect with $variable = str_replace('http://', '', $variable )
Related
I'm trying to get a very specific part of a URL using PHP so that I can use it as a variable later on.
The URL I have is:
https://forums.mydomain.com/index.php?/clubs/11-Default-Club
The particular part I am trying to extract is the 11 part between the /clubs/ and -Default-Club bits.
I was wondering what the best way to do this was. I've seen examples on here that use a regex-esque parser but I can't wrap my head around it for this particular instance.
Thanks
Edit; this is what I've tried so far using an explode query, but it seems to give me all sorts of elements which are not present in the URL above:
$url = $_SERVER['REQUEST_URI'];
$url = explode('/', $url);
$url = array_filter($url);
$url = array_merge($url, array());
Which returns:
Array ( [0] => index.php?app=core&module=system&controller=widgets&do=getBlock&blockID=plugin_9_bimBlankWidget_dqtr03ssz&pageApp=core&pageModule=clubs&pageController=view&pageArea=header&orientation=horizontal&csrfKey=8e19769b95c733b05439755827a98ac8 )
If you expect that the string with dashes (11-Default-Club) will be always at the end you can try this:
$url = $_SERVER['REQUEST_URI'];
$urlParts = explode('/', $url);
$string = end($urlParts);
$stringParts = explode('-', $string);
$theNumber = $stringParts[0]; // this will be 11
I'd rather be explicit:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$query = parse_url($url, PHP_URL_QUERY);
$pattern = '#^/clubs/(\d+)[a-zA-Z-]+$#';
$digits = preg_match($pattern, $query, $matches)
? $matches[1]
: null;
var_dump($digits);
Output:
string(2) "11"
If this URL structure is fix for all URLs in your site and you only want to get the integer/number/digit part of the URL:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$int = (int) filter_var($url, FILTER_SANITIZE_NUMBER_INT);
echo $int;
If this url structure is fix for all URLs in your site then below is best way to get your value.
<?php
$url = "https://forums.mydomain.com/index.php?/clubs/11-Default-Club";
$url = explode('/', $url);
$url = array_filter($url);
$end = end($url);
$end_parts = explode('-',$end);
echo $end_parts[0];
Output:
11
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'] : '');
}
I have a small problem with my tweets script. But for some reason, I don't know what the error could be. This is the error it gives me:
$url = "http://www.twitter.com/statuses/user_timeline/{$username}.xml?count={$number}";
$tweets = file_get_contents($url);
$feed = new SimpleXMLElement($tweets);
function time_stamp($date){
if (empty($date)){
return "No date provided";
}
and on the index.php page, it'll show this code:
<?php
$username = "user";//your twitter username
$number = 3;//number of tweets
include ("{$dir}/php/tweets.php");
?>
Do you guys know what it is that I'm doing wrong?
You don't need file_get_contents()
Try:
$url = "http://www.twitter.com/statuses/user_timeline/{$username}.xml?count={$number}";
$feed = simplexml_load_file($url);
Also, twitter made some changes not too long ago so your URL needs to look like this:
$url = "http://api.twitter.com/1/statuses/user_timeline/{$username}.xml?count={$number}";
Check this discussion.
You can use JSON easy and faster than XML
And to get content you can use
Curl => Faster
or
File_get_contents
Url
https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name={screenname}&count={count}
like this
<?php
$url = 'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=abdullaheid&count=3'
$x = file_get_contents( $url ) ; // Using file get contents
$object = json_decode( $x ) ;
$array = (array) $object ;
print_r( $array ) ;
?>
How to detect, if there is any URL in the text and title it has (if any)?
If there is one, then it should change the URL:
from: http://stackoverflow.com
into:
<detected:url="http://stackoverflow.com"/>
I need also to retrieve titles from external links like this example:
<title:http://stackoverflow.com/="the actual title from the stackoverflow"/>
This is for single URL case:
$url = "http://www.stackoverflow.com/";
$check_result = get_detected_and_title( $url );
function get_detected_and_title( $url )
{
$detected = '<detected:url="'.$url.'"/>';
$title = '';
$tmp_html = file_get_contents( $url );
preg_match('/<title>(.*)<\/title>/', $tmp_html, $res);
$title = '<title:'.$url.'="'.$res[1].'"/>';
return array( $detected, $title );
}
Actually, after looking through SO's pages, I think this is more close to what you looking for. Although it needs some adjustment: How to mimic StackOverflow Auto-Link Behavior
Lets say I have a youtube video url www.youtube.com/watch?v=B4CRkpBGQzU&feature=youtube_gdata&par1=1&par2=2
I want to get the video thumbnail -> i3.ytimg.com/vi/B4CRkpBGQzU/default.jpg
I just need a simple php script that I will input the $url and get the $img
If posible I would like to strip all other parameters and be left with just the
www.youtube.com/watch?v=B4CRkpBGQzU as the $url
To extract the identifier from the following URL :
$url = 'www.youtube.com/watch?v=B4CRkpBGQzU&feature=youtube_gdata&par1=1&par2=2';
You can first use parse_url() to get the query string :
$queryString = parse_url($url, PHP_URL_QUERY);
var_dump($queryString);
Which, here, would give you :
string 'v=B4CRkpBGQzU&feature=youtube_gdata&par1=1&par2=2' (length=49)
And, then, use parse_str() to extract the parameters from that query string :
parse_str($queryString, $params);
var_dump($params);
Which would get you the following array :
array
'v' => string 'B4CRkpBGQzU' (length=11)
'feature' => string 'youtube_gdata' (length=13)
'par1' => string '1' (length=1)
'par2' => string '2' (length=1)
And, now, it's just a matter of using the v item from that array, injecting it into the thumbnail URL :
if (isset($params['v'])) {
echo "i3.ytimg.com/vi/{$params['v']}/default.jpg";
}
Which gives :
i3.ytimg.com/vi/B4CRkpBGQzU/default.jpg
<?php
function getYoutubeImage($e){
//GET THE URL
$url = $e;
$queryString = parse_url($url, PHP_URL_QUERY);
parse_str($queryString, $params);
$v = $params['v'];
//DISPLAY THE IMAGE
if(strlen($v)>0){
echo "<img src='http://i3.ytimg.com/vi/$v/default.jpg' width='150' />";
}
}
?>
<?php
getYoutubeImage("http://www.youtube.com/watch?v=CXWSlho1mMY&feature=plcp");
?>
$url = "http://youtube.com/watch?v=B4CRkpBGQzU";
$url = explode("&", $url);
$vidID = preg_match("|?v=(.*)|", $url);
$thumb_default = file_get_contents("http://img.youtube.com/vi/$vidID/default.jpg");
$thumb1 = file_get_contents("http://img.youtube.com/vi/$vidID/0.jpg");
$thumb2 = file_get_contents("http://img.youtube.com/vi/$vidID/1.jpg");
$thumb3 = file_get_contents("http://img.youtube.com/vi/$vidID/2.jpg");
$thumb4 = file_get_contents("http://img.youtube.com/vi/$vidID/3.jpg");
Assuming youtube doesn't change their format:
$thumb = preg_match('/watch\?v=(.*)&feature/',$url, $matches);
This will get you the 'B4CRkpBGQzU' part in $matches[1];
Getting the video ID from the URL
$url = "http://www.youtube.com/watch?v=oHg5SJYRHA0&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ) );
echo $vidID;//this is video id
Getting the images
$thumb1 = file_get_contents("http://img.youtube.com/vi/$vidID/0.jpg");
$thumb2 = file_get_contents("http://img.youtube.com/vi/$vidID/1.jpg");
$thumb3 = file_get_contents("http://img.youtube.com/vi/$vidID/2.jpg");
$thumb4 = file_get_contents("http://img.youtube.com/vi/$vidID/3.jpg");