Archive for 'August, 2008'
Posted on August 30, 2008, Filled under PHP,
Bookmark it
Hello,
This function is useful to highlight words from a simple non-html text. For instance, the search results from your site can be highlighted.
<?php
// Credits: http://www.bitrepository.com/
function hightlight($str, $keywords = '')
{
$keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
$style = 'highlight';
$style_i = 'highlight_important';
/* Apply Style */
$var = '';
foreach(explode(' ', $keywords) as $keyword)
{
$replacement = "<span class='".$style."'>".$keyword."</span>";
$var .= $replacement." ";
$str = str_ireplace($keyword, $replacement, $str);
}
/* Apply Important Style */
$str = str_ireplace(rtrim($var), "<span class='".$style_i."'>".$keywords."</span>", $str);
return $str;
}
Don’t forget to define your style in the same file or in a separate one (recommended)!
.highlight
{
background: #CEDAEB;
}
.highlight_important
{
background: #F8DCB8;
}
Usage Example:
$str = 'The PHP development team would like to announce the immediate availability of a new PHP version.
The PDT project provides a PHP Development Tools framework for the Eclipse platform.
PHP is especially suited for Web development and can be embedded into HTML.
There are many development tools for PHP.';
$keywords = 'PHP development';
// tags from $keywords are automatically stripped
$string = hightlight($str, $keywords);
echo $string;
?>
As you can see the full string is highlighted with a different color than the words containing it.
Here’s how our example will look like:

IMPORTANT: This function only works for clean text, without any HTML in it (tags, escaping characters).
Your comments and suggestions are welcomed. Feel free to post them!
Good luck!
Posted on August 30, 2008, Filled under PHP,
Bookmark it
A function that generates an unique id. It’s useful when you need to generate keys that have to be unique.
<?php
function GenerateUniqueID()
{
return md5(uniqid(rand(),1));
}
echo GenerateUniqueID(); // returns a 32 characters unique string
?>
- August 30, 2008
- article by Gabriel C.
- 1 comment
Posted on August 30, 2008, Filled under PHP,
Bookmark it
Greetings,
This is a function which will help you to determine if a text starts which a specific string. It’s useful when you’re working with dynamic variables and you need to check if the text matches some patterns like its beginning. For instance you have an array and you want to output only files that have a prefix.
<?php
// Credits: http://www.bitrepository.com/
function begins_with($str, $text)
{
$rest = substr($text, 0, strlen($str));
if($rest == $str)
{
return true;
}
else
{
return false;
}
}
/* It could be a dynamic variable. Some names, locations, phone numbers etc.
have a prefix and this function can check it. */
$text = '05670-123456789'; // a sample phone number
$begin_str = '05670';
$check = begins_with($begin_str, $text);
if($check)
{
echo '"'.$text.'"'.' begins with "'.$begin_str.'"';
}
?>
- August 30, 2008
- article by Gabriel C.
- 1 comment
Posted on August 30, 2008, Filled under PHP,
Bookmark it
Here’s a piece of code that extracts images from an URL. This only works if the images are displayed using the IMG tag (not CSS).
This script only shows images. It doesn’t download any. The src attribute must have a full url in order for the images to show.
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
$url = 'http://www.microsoft.com/';
// Fetch page
$string = FetchPage($url);
// Regex that extracts the images (full tag)
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $string, $out, PREG_PATTERN_ORDER);
$img_tag_array = $out[0];
echo "<pre>"; print_r($img_tag_array); echo "</pre>";
// Regex for SRC Value
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex_src_url, $string, $out, PREG_PATTERN_ORDER);
$images_url_array = $out[1];
echo "<pre>"; print_r($images_url_array); echo "</pre>";
// Fetch Page Function
function FetchPage($path)
{
$file = fopen($path, "r");
if (!$file)
{
exit("The was a connection error!");
}
$data = '';
while (!feof($file))
{
// Extract the data from the file / url
$data .= fgets($file, 1024);
}
return $data;
}
?>
NOTE: You can use this script to extract images from local files too (not necessarily URLs).
Feel free to post any comments or suggestions regarding this script.
- August 30, 2008
- article by Gabriel C.
- 1 comment
Posted on August 30, 2008, Filled under PHP,
Bookmark it
This is a useful function if you need to validate a password (input). If you have a form and you need to check if the username, which is registering, entered a valid password (without illegal characters) then this would help you to do it. Only letters, numbers and underscores are accepted.
<?php
/*
Credits: http://www.bitrepository.com/
*/
// default chars values are defined
function validate_password($password, $min_char = 4, $max_char = 20)
{
// Remove whitespaces from the beginning and end of a string
$password = trim($password);
// Accept only letters, numbers and underscore
$eregi = eregi_replace('([a-zA-Z0-9_]{'.$min_char.','.$max_char.'})',
'', $password);
if(empty($eregi))
{
return true;
}
else
{
return false;
}
}
$password = 'my_password_123';
/*
First parameter: Password
Second parameter: Minimum chars
Third parameter: Maximum chars
*/
$validator = validate_password($password, 4, 20);
if($validator)
{
// Our current example will return true
echo 'The password is valid.';
}
else
{
/* if our password value is for instance: my_@#%_password
our function will return false */
echo 'The password appears to be invalid.
It should contain only letters, numbers and underscore.';
}
?>
Posted on August 29, 2008, Filled under PHP,
Bookmark it
Here’s a simple php function that calculates the age of someone, in years.
<?php
/*
Credits: http://www.bitrepository.com
URL: http://www.bitrepository.com/web-programming/php/simple-age-calculator.html
*/
function determine_age($birth_date)
{
$birth_date_time = strtotime($birth_date);
$to_date = date('m/d/Y', $birth_date_time);
list($birth_month, $birth_day, $birth_year) = explode('/', $to_date);
$now = time();
$current_year = date("Y");
$this_year_birth_date = $birth_month.'/'.$birth_day.'/'.$current_year;
$this_year_birth_date_timestamp = strtotime($this_year_birth_date);
$years_old = $current_year - $birth_year;
if($now < $this_year_birth_date_timestamp)
{
/* his/her birthday hasn't yet arrived this year */
$years_old = $years_old - 1;
}
return $years_old;
}
// You can write about any English textual datetime description
$birth_date = '1 May 1980';
$age = determine_age($birth_date);
echo $age;
?>
Posted on August 29, 2008, Filled under PHP,
Bookmark it
This snippet is useful when you need to replace multiple spaces from a string. Tabs, New Lines and Carriages are also replaced.
<?php
function replace_multiple_spaces($string)
{
// tabs, new lines and carriages are also replaced
$string = ereg_replace("[ \t\n\r]+", " ", $string);
return $string;
}
$string = "This
is
a dummy
text. ";
$new_string = replace_multiple_spaces($string);
// Outputs: This is a dummy text
echo $new_string;
?>
Posted on August 29, 2008, Filled under PHP,
Bookmark it
This is a Random Quote Script.
<?php
// Credits: http://www.bitrepository.com/
srand((float) microtime() * 10000000); // IF PHP Version < 4.2.0
// Create the array first
$quotes = array();
// Fill it with quotes
$quotes[] = array('quote' => 'Time is money.',
'author' => 'Benjamin Franklin');
$quotes[] = array('quote' => "And in the end, it's not the years
in your life that count.
It's the life in your years.",
'author' => 'Abraham Lincoln');
$quotes[] = array('quote' => "The secret to creativity is knowing
how to hide your sources.",
'author' => 'Albert Einstein');
$quotes[] = array('quote' => "A mind that is stretched by a new experience
can never go back to its old dimensions.",
'author' => 'Oliver Wendell Holmes');
/*
NOTE: To add more quotes just continue filling the array like this:
$quotes[] = array('quote' => "THE QUOTE HERE",
'author' => "QUOTES'S AUTHOR");
*/
$rand_key = array_rand($quotes, 1);
$quote_array = $quotes[$rand_key];
$quote = $quote_array['quote'];
$author = $quote_array['author'];
echo $quote.' - '.$author;
?>
Posted on August 29, 2008, Filled under PHP,
Bookmark it
The aim of this tutorial is to show you how to make SEO Friendly URLs. First of all you must check if your Apache Server has the mod_rewrite module enabled.
Too many parameters in an URL can create problems in crawling for a Search Engine. A friendly optimised URL would always be a better alternative if this option is available to you. These URLs are better indexed by Search Engines and people are more likely to click on static links which contain a description of what the link is about.
The rewriting rules should be written in the .htaccess file that must be created and uploaded in the main root of your site.
Here’s an example of a dynamic URL:
http://www.yourdomain.com/?c=5&p=20
A better (SEO) alternative of this URL would be:
http://www.yourdomain.com/articles/5/20-seo-techniques.html
You can obviously notice what this URL is about.
The server sends a request to the .htaccess file passing the category id and the post id.
The .htaccess file will look like this:
# Enable mod_rewrite
RewriteEngine On
# Sets the base URL for per-directory rewrites
RewriteBase /
RewriteRule ^articles/([0-9]+)/([0-9]+)-seo-techniques.html$ /?c=$1&p=$2
We use regular expressions to tell the script that only numbers values should be parsed. The static url is automatically converted to the dynamic one.
Here are more examples of rewrite rules:
RewriteRule ^terms-and-conditions.html$ /index.php?module=terms
# example: http://www.mydomain.com/category/10/post/35/php-functions.html
RewriteRule ^category/([0-9]+)/post/([0-9]+)/(.*).html$ /?c_id=$1&p_id=$2
By using this rewrite techniques your URLs are better indexed by search engines and are more likely to have a higher rank.
- August 29, 2008
- article by Gabriel C.
- 1 comment