Archive | December, 2007

Convert HTML to Entities or Entities to HTML

This is useful if you want to display your code to your website, blog or community forum.

<?php
$text = ‘<?php echo \’hello world\’; ?>’;

$encode = htmlentities($text);

$decode = html_entity_decode($encode);

echo ‘Encode ‘.$encode;
echo ‘<br />’;
echo ‘Decode ‘.$decode;
?>

Read more

PHP Even Function

Sample PHP Code that checks number if its Even.

<?php
function isEven($number){
$result = $number % 2;
if($result == 0){
return true;
}else{
return false;
}
}

$number = 24;

if(isEven($number)){
echo ‘The number is Even’;
}
?>

Output is
The number is Even

Read more

Javascript Back Button

This is the simple JavaScript back buttons navigation
button
<input onclick="history.go(-1)" type="button" />
Link
<a onclick="history.go(-1)" href="#back">Back</a>
Image
<img onclick="history.go(-1)" src="images/back.gif" />

Read more

How to cut the string without breaking any words

<?php
function Cut($string, $max_length){
if (strlen($string) > $max_length){
$string = substr($string, 0, $max_length);
$pos = strrpos($string, ” “);
if($pos === false) {
return substr($string, 0, $max_length).”…”;
}
return substr($string, 0, $pos).”…”;
}else{
return $string;
}
}

$string = ‘How to cut the string without breaking any words’;
echo Cut($string,30);

?>

The output is
How to cut the string without…

Read more

Getting a file extension using PHP

<?php
function getExt($filename){
return substr(strrchr($filename, ‘.’), 1);
}

$file = ‘myphoto.jpg’;

echo getExt($file);

?>

The output is
jpg

Read more

PHP matching string

We can match string in PHP using strrpos function here is the sample code

<?php
function Match($keyword,$subject){
if(strrpos($subject,$keyword)===false){
return false;
}else{
return true;
}
}

$keyword = ‘insicdesigns.com’;
$subject = ‘I love insicdesigns.com’;

if(Match($keyword,$subject)){
echo ‘Match!’;
}else{
echo ‘Not found’;
}

?>

It will display…
Match!

Read more

PHP Email Validation

Email validation is very important in application development. Here I show you a sample PHP code on how to validate email address.

<?php
function isEmail($email){
if(!eregi(“^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$”, $email)){
return false;
}else{
return true;
}
}

$email = ‘test@test’;

if(!isEmail($email)){
echo ‘Invalid email address’;
}else{
echo ‘Ok’;
}

?>

The output is…
Invalid email address
As simple as that. Try it by yourself.

Read more

PHP Random Numbers & letters

This is the simple function of generating a random numbers in php.

<?php
function Random($length=5){
$key = ”;
$pattern = “12345678901234567890123456789012345678901234567890″;
for($i=0;$i

Read more