Archive for 'October, 2008'

PHP: Extract Alphabetical Sequences from a String

Posted on October 5, 2008, Filled under PHP,  Bookmark it

This function extracts alphabetical sequences (usually words) from a string (text):

function extract_alphabetical_sequences($string)
{
preg_match_all('/([a-zA-Z]+)/', $string, $match);

return $match[0];
}

$string = 'In hac habitasse platea dictumst. 54 8*5 5#$&*^@  $ @ In eget sem. Etiam quam. Nam nec, justo sed lorem, auctor tincidunt. Nulla id risus laoreet nisl  *^$&&@#$ egestas ultrices.';

$alpha_array = extract_alphabetical_sequences($string);

echo '<pre>'; print_r($alpha_array); echo "</pre>";

Output:

Array
(
    [0] => In
    [1] => hac
    [2] => habitasse
    [3] => platea
    [4] => dictumst
    [5] => In
    [6] => eget
    [7] => sem
    [8] => Etiam
    [9] => quam
    [10] => Nam
    [11] => nec
    [12] => justo
    [13] => sed
    [14] => lorem
    [15] => auctor
    [16] => tincidunt
    [17] => Nulla
    [18] => id
    [19] => risus
    [20] => laoreet
    [21] => nisl
    [22] => egestas
    [23] => ultrices
)

If you need to extract all the words from a string, consider using the str_word_count() function.

PHP: How to extract numbers from a string (text)

Posted on October 5, 2008, Filled under PHP,  Bookmark it

This is a short function that extracts numbers from a string:

function extract_numbers($string)
{
preg_match_all('/([\d]+)/', $string, $match);

return $match[0];
}

$string = 'Lorem ipsum dolor sit 45 40 amet, consectetuer adipiscing elit. 35 65675 Suspendisse sed nibh non diam consectetuer pharetra. Morbi ultricies 235 536pede et pede. 9432 3536 Nunc eu risus eget quam lacinia feugiat. In sapien sem, fringilla quis, 34 24 8762condimentum id, bibendum ut, nibh. Quisque 2367 784 elementum massa 350 235 vel nulla.';

$numbers_array = extract_numbers($string);

echo '<pre>'; print_r($numbers_array); echo "</pre>";

Output:

Array
(
    [0] => 45
    [1] => 40
    [2] => 35
    [3] => 65675
    [4] => 235
    [5] => 536
    [6] => 9432
    [7] => 3536
    [8] => 34
    [9] => 24
    [10] => 8762
    [11] => 2367
    [12] => 784
    [13] => 350
    [14] => 235
)

Here’s a snippet that extracts elements from an array starting with a specific letter (alphabetical search).

$programming_languages = array('A+', 'A++', 'A# .NET', 'A# (Axiom)', 'A-0', 'B', 'Baja', 'BeanShell', 'C#', 'Cayenne', 'JavaScript', 'Java', 'JScript', 'Python', 'Perl', 'PHP', 'Visual Basic .NET', 'Visual FoxPro', 'ZOPL', 'ZPL');

function alpha_search($array, $letter = 'a') // 'a' is the default value
{
return array_filter($array, create_function('$var', 'return (strtolower(trim($var{0})) == strtolower("'.$letter.'"));'));
}

/* Values starting with 'A' */
echo '<pre>'; print_r(alpha_search($programming_languages, 'a'));  echo '</pre>'; 

/* Values starting with 'V' */
echo '<pre>'; print_r(alpha_search($programming_languages, 'v'));  echo '</pre>';

NOTE: In the second argument you can use either a lower case letter or an upper case letter. It’s case insensitive.

Here’s how our sample ouput will look like:

Array
(
    [0] => A+
    [1] => A++
    [2] => A# .NET
    [3] => A# (Axiom)
    [4] => A-0
)

Array
(
    [16] => Visual Basic .NET
    [17] => Visual FoxPro
)

PHP: Equivalent of trim() Function for Arrays

Posted on October 5, 2008, Filled under PHP,  Bookmark it

This function strips the null element values from the beginning and ending of an array. For instance, this snippet is useful when you use file(), which reads an entire file into an array and in the beginning / ending of the file there are blank lines that need to be stripped.

function trim_array($array, $keep_keys = false)
{
$i = 0;

   foreach($array as $key => $value)
   {
   $value = trim($value);

   if($value) break;

if($keep_keys) unset($array[$key]);

   $i++;
   }

if($i > 0 && !$keep_keys)
{
	array_splice($array, 0, $i);
}

$reverse = array_reverse($array, true);

$i = 0;

   foreach($reverse as $key => $value)
   {
   $value = trim($value);

   if($value) break;

   if($keep_keys) unset($array[$key]);

   $i++;
   }

if($i > 0 && !$keep_keys)
{
	array_splice($array, -$i);
}

return $array;
}

$array = array(' ', ' ' , ' ', "n", "r", 1, 2 , 5 , 7, ' ', ' ', ' ', 10, 11, 12, 13, ' ', "r", "n", " ", " ");

echo "<pre>"; print_r($array); echo "</pre>";

/*
First Argument: The Array
Second Argument: New keys? false = the current keys will be kept, true= new keys will be assigned to the array (default is set to 'false')
*/

echo "<pre>"; print_r(trim_array($array, true)); echo "</pre>";

NOTE: In the second argument of trim_array() you can specify if you wish to keep the initial array keys (true = will keep the keys, false = will assign new ones). The default value is ‘false’, meaning that new keys will be assigned to the array.

In 29 May 1999, Graham Rawlinson wrote a letter to New Scientist, commenting about a research made by 2 scientists: Kourosh Saberi and David Perrott. Here’s an excerpt from that letter:

You report that reversing 50-millisecond segments of recorded sound does not greatly affect listeners’ ability to understand speech (In Brief, 1 May, p 27). This reminds me of my PhD at Nottingham University (1976), which showed that randomising letters in the middle of words had little or no effect on the ability of skilled readers to understand the text. Indeed one rapid reader noticed only four or five errors in an A4 page of muddled text.

Aoccdrnig to rscheearch at an Elingsh uinervtisy, it deosn’t mttaer in waht oredr the ltteers in a wrod are, olny taht the frist and lsat ltteres are at the rghit pcleas. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by ilstef, but the wrod as a wlohe.

Here’s a function that converts a normal text into a scrambled one, but still readable:

/*
Credits: Bit Repository

URL: http://www.bitrepository.com/web-programming/php/randomize-middle-letters-keeping-the-word-readable.html
*/
function scramble_text($text)
{
$text = ereg_replace('([^A-Za-z0-9])', " \1", $text);

$keywords = preg_split("/ /", $text);

preg_match_all("/([A-Za-z]{4,})/", $text, $match);

foreach($match[0] as $value)
{
	if(in_array($value, $keywords))
	{
		/* [NEW SCRAMBLED WORD BEGIN] */

		$new_scrambled_word = $value[0];

		/* Middle Letters Scramble */

		$middle_letters = substr($value, 1, -1);

		if(strlen($middle_letters) == 2)
		{
        $new_scrambled_word .= $middle_letters[strlen($middle_letters) - 1].$middle_letters[0];
		}
		else
		{
		   $chars = preg_split('//', $middle_letters, -1, PREG_SPLIT_NO_EMPTY);

		   shuffle($chars);

		   foreach($chars as $char)
		   {
		      $new_scrambled_word .= $char;
		   }
		}

		$new_scrambled_word .= $value[strlen($value) - 1];

		/* [NEW SCRAMBLED WORD END] */

		$key = array_search($value, $keywords);

        $keywords[$key] = $new_scrambled_word;
	}
}

/* The $keywords array now contains the scrambled words */

$new_text = '';

foreach($keywords as $value)
	{
        $new_text .= ($value) ? $value : ' ';
	}

	$new_text = trim($new_text);

	return $new_text;
}

$text = 'The goal of the PHP language is to allow web developers to write dynamically generated pages quickly.';

$scrambled_and_readable = scramble_text($text);

echo $scrambled_and_readable;

/*
Possible output:

The gaol of the PHP lguanage is, to aollw web dpleeovers to wirte dmncalyaily gaeenertd peags qcikuly.
*/

PHP: How to create a Tag Cloud

Posted on October 3, 2008, Filled under PHP,  Bookmark it

This is a tutorial that will give you an idea of how to create a Tag Cloud and implemented it the pages of your website.

Let’s start creating the necessary files:

config.php

The $factor variable is used in the mathematical operation which calculates the importance of a tag (index.php, line 81). It calculates the average text size of the tags. Increasing this value will make the text size to increase as well. Decreasing will do reverse.

In $starting_font_size we set the minimal font size that a tag can have. This variable is also used to calculate the importance of the tag.

We need a separator that will be placed between the tags. In $tag_separator its value must be set.

Do you wish to show the tags in random order? Set $random_order to TRUE (if yes) or FALSE (if not).

<?php
// Incresing this number will make the words bigger;
// Decreasing will do reverse

$factor = 0.5;

// Smallest font size possible

$starting_font_size = 12;

// Tag Separator

$tag_separator = '&nbsp; &nbsp; &nbsp;';

// Display items in random order?

$random_order = true;
?>

functions.php

This function is used to randomly reorder the elements of an array.

<?php
function randomize_array($array)
{
$rand_items = array_rand($array, count($array));

$new_array = array();

foreach($rand_items as $value)
	{
	$new_array[$value] = $array[$value];
	}

	return $new_array;
}
?>

Let’s add some style to our tag cloud!

style.css

HTML, BODY
{
padding: 0;
border: 0px none;
font-family: Verdana;
font-weight: none;
}

.tags_div
{
padding: 3px;
border: 1px solid #A8A8C3;
background-color: white;
width: 500px;
-moz-border-radius: 5px;
}

H1
{
font-size: 16px;
font-weight: none;
}

A:link
{
color: #676F9D;
text-decoration: none;
}

A:hover
{
text-decoration: none;
background-color: #4F5AA1;
color: white;
}

index.php

For our tag cloud sample I’ve used a list of top programming languages from TIOBE Software.

The list is stored in an array ($languages) that contains the names of the programming languages (the keys of the array) and their ratings (the values of the array). The second array, $languages_wiki is used to set links for our tags (the addresses are from Wikipedia having information about the programming languages from the list).

As you can see the total sum of the values is calculated (in our case it’s 94.732). This is used in the mathematical operation that will calculate the importance of a tag. It’s obvious that JAVA (20.715), compared to Delphi (3.130), is a more important tag representing 22% from the total sum of the ratings, while Delphi only 3%.

<?php
include_once 'config.php';
include_once 'functions.php';

$languages = array('PHP'            => '9.243',
                   'Python'         => '5.012',
                   'ActionScript'   => '0.472',
                   'Lisp/Scheme'    => '0.419',
                   'Lua'            => '0.415',
                   'Pascal'         => '0.400',
                   'Java'           => '20.715',
                   'PowerShell'     => '0.384',
                   'COBOL'          => '0.360',
                   'SAS'            => '0.640',
                   'JavaScript'     => '3.130',
                   'PL/SQL'         => '0.700',
                   '(Visual) Basic' => '10.490',
                   'D'              => '1.265',
                   'Ruby'           => '2.762',
                   'Delphi'         => '3.055',
                   'C#'             => '4.334',
                   'Perl'           => '4.841',
                   'C++'            => '10.716',
                   'C'              => '15.379');

$languages_wiki = array('PHP'       => 'PHP',
                   'Python'         => 'Python_(programming_language)',
                   'ActionScript'   => 'ActionScript',
                   'Lisp/Scheme'    => 'Lisp_(programming_language)',
                   'Lua'            => 'Lua_(programming_language)',
                   'Pascal'         => 'Pascal_Programming_Language',
                   'Java'           => 'Java',
                   'PowerShell'     => 'PowerShell',
                   'COBOL'          => 'COBOL',
                   'SAS'            => 'SAS_programming_language',
                   'JavaScript'     => 'JavaScript',
                   'PL/SQL'         => 'PL/SQL',
                   '(Visual) Basic' => 'Visual_Basic',
                   'D'              => 'D_programming_language',
                   'Ruby'           => 'Ruby',
                   'Delphi'         => 'Delphi',
                   'C#'             => 'C_Sharp_(programming_language)',
                   'Perl'           => 'Perl',
                   'C++'            => 'C%2B%2B',
                   'C'              => 'C_programming');

$max_count = array_sum($languages);

if($random_order)
{
$languages = randomize_array($languages);
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> Tag Cloud Generator </TITLE>

  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="tag, cloud">
  <META NAME="Description" CONTENT="A Tag Cloud Example">

<LINK REL="stylesheet" HREF="style.css" TYPE="text/css">

 </HEAD>

 <BODY>

 </BODY>
</HTML>

<!-- Add some style to the DIV -->

<center><h1>Tag Cloud Example</h1><div align='center' class='tags_div'>

<?php
foreach($languages as $language => $rating)
{
$x = round(($rating * 100) / $max_count) * $factor;

$font_size = $starting_font_size + $x.'px';

echo "<span style='font-size: ".$font_size."; color: #676F9D;'>
<a href='http://en.wikipedia.org/wiki/".$languages_wiki[$language]."'>".$language."</a></span>".$tag_separator;
}
?>

</div></center>

Example #1 (with factor equal with 0.5)

Example #2 (with factor equal with 1 and mouse cursor over ‘Ruby’)

You can use this model to create tag clouds from arrays that are created from MySQL Selects or from Flat Files Databases.

Display Values from an Array in Random Order

Posted on October 2, 2008, Filled under PHP,  Bookmark it

This is a function that randomizes the order of the elements in an array.

<?php
function randomize_array($array)
{
$rand_items = array_rand($array, count($array));

$new_array = array();

foreach($rand_items as $value)
	{
	$new_array[$value] = $array[$value];
	}

	return $new_array;
}

$array = array('sleep' => 'Delay execution',
                    'show_source' => 'alias for highlight_file()',
                    'str_ireplace' => 'PHP5 Function',
                    'sizeof' => 'Alias for count',
                    'parse_url' => 'Parse a URL and return its components');

echo "<pre>"; print_r($array); echo "</pre>";

echo "<pre>"; print_r(randomize_array($array)); echo "</pre>";

/*
-- Initial Array

Array
(
    [sleep] => Delay execution
    [show_source] => alias for highlight_file()
    [str_ireplace] => PHP5 Function
    [sizeof] => Alias for count
    [parse_url] => Parse a URL and return its components
)

-- An example of a random result

Array
(
    [sizeof] => Alias for count
    [parse_url] => Parse a URL and return its components
    [sleep] => Delay execution
    [str_ireplace] => PHP5 Function
    [show_source] => alias for highlight_file()
)
*/
?>

NOTE: A similar function in PHP is shuffle() which assigns new keys to elements in the array. It removes any existing keys that may have been assigned, instead of just reordering them as our randomize_array() function does.

PHP: Cropping a Rectangle Image to Square using GD

Posted on October 1, 2008, Filled under PHP,  Bookmark it

Hello coders,

This is a PHP Class that crops images (rectangles) to squares using the GD library. First, make sure you have this extension enabled. This can be verified using the following code:

check_gd.php

<?php
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit("The GD extension is not loaded.");
    }
}
?>

The class checks if the image is already a square. If it is, it will output a message to the user. If it’s not it will calculate the necessary coordinates and crop it: to left, center or right (default is ‘center’).

crop.image.to.square.class.php

<?php
/*
--------------------------------------------------------------------------------------------
Credits: Bit Repository 

Source URL: http://www.bitrepository.com/web-programming/php/crop-rectangle-to-square.html
--------------------------------------------------------------------------------------------
*/ 

/* Crop Image Class */

class Crop_Image_To_Square {

var $source_image;
var $new_image_name;
var $save_to_folder;

function crop($location = 'center')
{
$info = GetImageSize($this->source_image);

$width = $info[0];
$height = $info[1];
$mime = $info['mime'];

if($width == $height)
{
echo 'The source image is already a square.';
}
else
{
// 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';
}

// Coordinates calculator

   if($width > $height) // Horizontal Rectangle?
   {
	   if($location == 'center')
       {
       $x_pos = ($width - $height) / 2;
       $x_pos = ceil($x_pos);

       $y_pos = 0;
	   }
	   else if($location == 'left')
	   {
	   $x_pos = 0;
	   $y_pos = 0;
	   }
	   else if($location == 'right')
	   {
	   $x_pos = ($width - $height);
	   $y_pos = 0;
	   }

       $new_width = $height;
       $new_height = $height;
   }
   else if($height > $width) // Vertical Rectangle?
   {
	   if($location == 'center')
       {
       $x_pos = 0;

       $y_pos = ($height - $width) / 2;
       $y_pos = ceil($y_pos);
       }
	   else if($location == 'left')
	   {
	   $x_pos = 0;
	   $y_pos = 0;
	   }
	   else if($location == 'right')
	   {
	   $x_pos = 0;
	   $y_pos = ($height - $width);
	   }

       $new_width = $width;
       $new_height = $width;

   }

$image = $image_create_func($this->source_image);

$new_image = ImageCreateTrueColor($new_width, $new_height);

// Crop to Square using the given dimensions
ImageCopy($new_image, $image, 0, 0, $x_pos, $y_pos, $width, $height);

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) ).'_square_'.$location.'.'.$new_image_ext;
	       }

		$save_path = $this->save_to_folder.$new_name;
		}
		else
		{
		/* Show the image (on the fly) 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;
	}
}
?>
Variables Info

$source – Here we set the full path (i.e. /home/www.mysite.com/public_html/images/myrectangle.jpg) to the rectangle image we wish to crop. If the image is in the same folder with the class, then you can just set the filename as the path (i.e. myrectangle.jpg).

$new_image_name – It’s used to set a name for the new cropped image. If it’s not set a name will be assigned automatically.

$save_to_folder – The path to the folder where the square image will be saved. Make sure it’s writable (0777). It no folder is set the new square image will show in the browser (on the fly) without being saved.

This is an usage example of this class:

example.php

<?php
include 'crop.image.to.square.class.php';

$crop = new Crop_Image_To_Square;
$crop->source_image = 'my_rectangle_image.jpg';

$crop->save_to_folder = 'square_images/';

/* left, center or right; If none is set, center will be used as default */
$process = $crop->crop('right');

if($process['result'])
{
echo 'The rectangle image ('.$process['new_file_path'].') was cropped.';
}
?>

If you’re interested in resizing an image (i.e. to square) consider checking our post regarding images resizing.