Thursday, April 02, 2009

Javascript get domain name from URL or email

I've made a simple script that will retrieve the domain name of a given site url or an email.


function getDomainName(urlOrEmail)
{
var matches = urlOrEmail.match(/^([\w]+:\/{0,2})?([\w]+\.|.*@)?([\w]+\.[\w]{2,4})(\/?)(.*)?/);

return matches && matches[3] ;


}


Sample usage:

//any format such as images.photosnippet.com, www.photosnippet.com, etc
var site = "http://www.photosnippet.com";
var email = "me@photosnippet.com";

document.write(getDomainName(site)); => prints "photosnippet.com"
document.write(getDomainName(email)); => prints "photosnippet.com"

NOTE: Thist post has been updated. Thanks to "gwafo ko" comments, I was able to know more regex syntax such as "\w" and "String.match()". (obviously this was my first regex code. hehe ;) ).

I used this site as reference: http://www.regular-expressions.info/reference.html

What the script above does is that it will only retrieve the domain name, excluding subdomains. Here are the different scenarios that this script was intended for:

1. me@markglibres.com
2. my.projects@markglibres.com
3. mailto::me@markglibres.com
4. markglibres.com
5. www.markglibres.com
6. projects.markglibres.com
7. http://markglibres.com
8. http://projects.markglibres.com

This also has a strict rule of only having valid domain extensions such as ".com" or ".us" or ".info" (characters not greater than 4 characters)

This will return "markglibres.com"

Sunday, March 29, 2009

PHP Image Resize Transparency

I've made a very simple script that will retain transparency of images especially when resizing.

NOTE: Transparency is only supported on GIF and PNG files.

Parameters:

$new_image = image resource identifier such as returned by imagecreatetruecolor(). must be passed by reference


$image_source = image resource identifier returned by imagecreatefromjpeg, imagecreatefromgif and imagecreatefrompng. must be passed by reference

function setTransparency($new_image,$image_source)
{
      $transparencyIndex = imagecolortransparent($image_source);
       $transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);

      if ($transparencyIndex >= 0) {
          $transparencyColor = imagecolorsforindex($image_source, $transparencyIndex);
      }

      $transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
      imagefill($new_image, 0, 0, $transparencyIndex);
      imagecolortransparent($new_image, $transparencyIndex);
}


Sample Usage: (resizing)

$image_source = imagecreatefrompng('test.png');
$new_image = imagecreatetruecolor($new_width, $new_height);
setTransparency($new_image,$image_source);
imagecopyresampled($new_image, $image_source, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
imagepng($new_image,'resizetest.png');