Posted on October 27, 2008, Filled under AJAX,
Bookmark it
This is a great star rating system from Nomadic Functions. Compared to other traditional rating scripts, this one has a 1,680% increase in accuracy and 84 hot spots (84px wide), instead of only 5. To view a live demo & download the source code visit: http://www.nofunc.com/AJAX_Star_Rating/.
Posted on October 26, 2008, Filled under PHP,
Bookmark it
This is a PHP Class useful if you need to filter (bad, naughty) words from a string (text), whether is a simple string or one containing HTML tags.
Here’s the complete source code (we will explain it below):
filter.string.class.php
<?php
/*
Credits: Bit Repository
*/
class Filter_String {
var $strings;
var $text;
var $keep_first_last;
var $replace_matches_inside_words;
function filter()
{
$new_text = '';
$regex = '/<\/?(?:\w+(?:=["\'][^\'"]*["\'])?\s*)*>/'; // Tag Extractor
preg_match_all($regex, $this->text, $out, PREG_OFFSET_CAPTURE);
$array = $out[0];
if(!empty($array))
{
if($array[0][1] > 0)
{
$new_text .= $this->do_filter(substr($this->text, 0, $array[0][1]));
}
foreach($array as $value)
{
$tag = $value[0];
$offset = $value[1];
$strlen = strlen($tag); // characters length of the tag
$start_str_pos = ($offset + $strlen); // start position for the non-tag element
$next = next($array);
// end position for the non-tag element
$end_str_pos = $next[1];
// no end position?
// This is the last text from the string and it is not followed by any tags
if(!$end_str_pos) $end_str_pos = strlen($this->text);
// Start constructing the new resulted string. We'll add tags now!
$new_text .= substr($this->text, $offset, $strlen);
$diff = ($end_str_pos - $start_str_pos);
// Is this a simple string without any tags? Apply the filter to it
if($diff > 0)
{
$str = substr($this->text, $start_str_pos, $diff);
$str = $this->do_filter($str);
$new_text .= $str; // Continue constructing the text with the (filtered) text
}
}
}
else // No tags were found in the string? Just apply the filter
{
$new_text = $this->do_filter($this->text);
}
return $new_text;
}
function do_filter($var)
{
if(is_string($this->strings)) $this->strings = array($this->strings);
foreach($this->strings as $word)
{
$word = trim($word);
$replacement = '';
$str = strlen($word);
$first = ($this->keep_first_last) ? $word[0] : '';
$str = ($this->keep_first_last) ? $str - 2 : $str;
$last = ($this->keep_first_last) ? $word[strlen($word) - 1] : '';
$replacement = str_repeat('*', $str);
if($this->replace_matches_inside_words)
{
$var = str_replace($word, $first.$replacement.$last, $var);
}
else
{
$var = preg_replace('/\b'.$word.'\b/i', $first.$replacement.$last, $var);
}
}
return $var;
}
}
?>
Read more from this entry…
Posted on October 15, 2008, Filled under JavaScript,
Bookmark it
This is a JavaScript function that works like array_combine() in PHP. Below you have the function and a usage example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Equivalent of PHP's array_combine() | JavaScript Library</TITLE>
<META NAME="Author" CONTENT="Bit Repository">
<META NAME="Keywords" CONTENT="array_combine, php, javascript">
<META NAME="Description" CONTENT="Equivalent of PHP's array_combine() | JavaScript Library">
<SCRIPT LANGUAGE="JavaScript">
var first_array = new Array('green', 'red', 'yellow');
var second_array = new Array('avocado', 'apple', 'banana');
/*
// Alternative way of creating the arrays
var first_array = new Array();
first_array[0] = "green";
first_array[1] = "red";
first_array[2] = "yellow";
var second_array = new Array();
second_array[0] = "avocado";
second_array[1] = "apple";
second_array[2] = "banana";
*/
/*
Parameters: a - array of keys to be used, b - array of values to be used
IMPORTANT: The number of elements for each array must be equal
*/
function array_combine(a, b)
{
if(a.length != b.length)
{
return false;
}
else
{
new_array = new Array();
for (i = 0; i < a.length; i++)
{
new_array[a[i]] = b[i];
}
return new_array;
}
}
var combined_array = array_combine(first_array, second_array);
// Let's print the array in PHP's style
document.write("Array<br>{<br>");
for (key in combined_array)
{
document.write("[" + key + "] => " + combined_array[key] + "<br>");
}
document.write("}<br>");
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
The output will be like the one resulted from the print_r() function in PHP:
echo "<pre>"; print_r($combined_array); echo "</pre>";
Array
{
[green] => avocado
[red] => apple
[yellow] => banana
}
Posted on October 13, 2008, Filled under PHP,
Bookmark it
This is a PHP Class useful if you need to add transparency to an image. Have a look at the source code and the explanations below:
class.image.transparency.php
<?php
/*
---------------------------------------------------------------------------------------------
Credits: Bit Repository
Source URL: http://www.bitrepository.com/web-programming/php/image-transparency-with-gd.html
---------------------------------------------------------------------------------------------
*/
/* Image Transparency Class */
class Image_Transparency {
var $source_image;
var $pct;
var $new_image_name;
var $save_to_folder;
function make_transparent()
{
$info = GetImageSize($this->source_image);
$width = $info[0];
$height = $info[1];
$mime = $info['mime'];
// What sort of image?
$type = substr(strrchr($mime, '/'), 1);
switch ($type)
{
case 'jpeg':
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$new_image_ext = 'jpg';
break;
case 'png':
$image_create_func = 'ImageCreateFromPNG';
$image_save_func = 'ImagePNG';
$new_image_ext = 'png';
break;
case 'bmp':
$image_create_func = 'ImageCreateFromBMP';
$image_save_func = 'ImageBMP';
$new_image_ext = 'bmp';
break;
case 'gif':
$image_create_func = 'ImageCreateFromGIF';
$image_save_func = 'ImageGIF';
$new_image_ext = 'gif';
break;
case 'vnd.wap.wbmp':
$image_create_func = 'ImageCreateFromWBMP';
$image_save_func = 'ImageWBMP';
$new_image_ext = 'bmp';
break;
case 'xbm':
$image_create_func = 'ImageCreateFromXBM';
$image_save_func = 'ImageXBM';
$new_image_ext = 'xbm';
break;
default:
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$new_image_ext = 'jpg';
}
// Source Image
$image = $image_create_func($this->source_image);
$new_image = ImageCreateTruecolor($width, $height);
// Set a White & Transparent Background Color
$bg = ImageColorAllocateAlpha($new_image, 255, 255, 255, 127); // (PHP 4 >= 4.3.2, PHP 5)
ImageFill($new_image, 0, 0 , $bg);
// Copy and merge
ImageCopyMerge($new_image, $image, 0, 0, 0, 0, $width, $height, $this->pct);
if($this->save_to_folder)
{
if($this->new_image_name)
{
$new_name = $this->new_image_name.'.'.$new_image_ext;
}
else
{
$new_name = $this->new_image_name(basename($this->source_image)).'_transparent'.'.'.$new_image_ext;
}
$save_path = $this->save_to_folder.$new_name;
}
else
{
/* Show the image without saving it to a folder */
header("Content-Type: ".$mime);
$image_save_func($new_image);
$save_path = '';
}
// Save image
$process = $image_save_func($new_image, $save_path) or die("There was a problem in saving the new file.");
return array('result' => $process, 'new_file_path' => $save_path);
}
function new_image_name($filename)
{
$string = trim($filename);
$string = strtolower($string);
$string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
$string = ereg_replace("[ \t\n\r]+", "_", $string);
$string = str_replace(" ", '_', $string);
$string = ereg_replace("[ _]+", "_", $string);
return $string;
}
}
?>
Read more from this entry…
Posted on October 6, 2008, Filled under PHP,
Bookmark it
This is a short snippet useful to detect if the visitor uses Google Chrome Browser.
<?php
function is_chrome()
{
return(eregi("chrome", $_SERVER['HTTP_USER_AGENT']));
}
if(is_chrome())
{
// code for Chrome Browser here
echo 'You are using Google Chrome Browser.';
}
?>
Posted on October 6, 2008, Filled under PHP,
Bookmark it
This is a snippet that finds e-mail addresses from a string using a regexp and converts them into clickable links.
<?php
function convert_emails_to_clickable_links($text)
{
$regex = "([a-z0-9_\-\.]+)". # name
"@". # at
"([a-z0-9-]{1,64})". # domain
"\.". # period
"([a-z]{2,10})"; # domain extension
$text = eregi_replace($regex, '<a href="mailto:\\1@\\2.\\3">\\1@\\2.\\3</a>', $text);
return $text;
}
$text = 'You can contact me at: example-name@mysite.com. My alternative address is other-username@domain.com.';
echo convert_emails_to_clickable_links($text);
/*
You can contact me at: <a href="mailto:example-name@mysite.com">example-name@mysite.com</a>. My alternative address is <a href="mailto:other-username@domain.com">other-username@domain.com</a>.
?>
*/
Posted on October 5, 2008, Filled under PHP,
Bookmark it
This is a function that selects files from a directory and orders them by the last time they were changed, in ascending or descending order. The snippet also calculates how much time passed since the file’s content was changed.
function Sort_Directory_Files_By_Last_Modified($dir, $sort_type = 'descending', $date_format = "F d Y H:i:s.")
{
$files = scandir($dir);
$array = array();
foreach($files as $file)
{
if($file != '.' && $file != '..')
{
$now = time();
$last_modified = filemtime($dir.$file);
$time_passed_array = array();
$diff = $now - $last_modified;
$days = floor($diff / (3600 * 24));
if($days)
{
$time_passed_array['days'] = $days;
}
$diff = $diff - ($days * 3600 * 24);
$hours = floor($diff / 3600);
if($hours)
{
$time_passed_array['hours'] = $hours;
}
$diff = $diff - (3600 * $hours);
$minutes = floor($diff / 60);
if($minutes)
{
$time_passed_array['minutes'] = $minutes;
}
$seconds = $diff - ($minutes * 60);
$time_passed_array['seconds'] = $seconds;
$array[] = array('file' => $file,
'timestamp' => $last_modified,
'date' => date ($date_format, $last_modified),
'time_passed' => $time_passed_array);
}
}
usort($array, create_function('$a, $b', 'return strcmp($a["timestamp"], $b["timestamp"]);'));
if($sort_type == 'descending')
{
krsort($array);
}
return array($array, $sort_type);
}
Read more from this entry…
Posted on October 5, 2008, Filled under PHP,
Bookmark it
This is a snippet that matches non-alphanumeric characters from a string (text).
<?php
function match_non_alphanumeric_characters($string, $strip_space = true) // Match spaces?
{
$str = ($strip_space) ? ' ' : '';
preg_match_all('/([^a-zA-Z0-9'.$str.']+)/', $string, $match);
return $match[0];
}
$string = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent porttitor euismod enim # Sed posuere & Duis non elit * Sed tempus dolor$';
$non_alphanumeric_array = match_non_alphanumeric_characters($string);
echo '<pre>'; print_r($non_alphanumeric_array); echo "</pre>";
?>
Output:
Array
(
[0] => ,
[1] => .
[2] => #
[3] => &
[4] => *
[5] => $
)
Posted on October 5, 2008, Filled under PHP,
Bookmark it
This short snippet is useful if you need to extract alphanumeric sequences (characters) from a string:
function extract_alphanumeric_sequences($string)
{
preg_match_all('/([a-zA-Z0-9]+)/', $string, $match);
return $match[0];
}
$string = 'Suspendisse 354 65pretium eros ut 43564 mauris. Integer in lacus quis est dignissim posuere. Aenean dui. &$#^@ %$ 94375 Mauris non turpis sit amet nunc imperdiet varius.';
$alpha_array = extract_alphanumeric_sequences($string);
echo '<pre>'; print_r($alpha_array); echo "</pre>";
Output:
Array
(
[0] => Suspendisse
[1] => 354
[2] => 65pretium
[3] => eros
[4] => ut
[5] => 43564
[6] => mauris
[7] => Integer
[8] => in
[9] => lacus
[10] => quis
[11] => est
[12] => dignissim
[13] => posuere
[14] => Aenean
[15] => dui
[16] => 94375
[17] => Mauris
[18] => non
[19] => turpis
[20] => sit
[21] => amet
[22] => nunc
[23] => imperdiet
[24] => varius
)