Thursday, March 28, 2013

Basic Regular Expression Patterns II

Here I'll be discussing some common problems which can be solved with Regular expressions in Javascript.


1. Problem : Check whether a given phone number is in (xxx)xxx-xxx format.
   Answer :
   var patt = /^\([0-9]{3}\)[0-9]{3}-[0-9]{3}$/;
 patt.test("(123)456-678");  // true

  
   Note : The character "(" has been denoted as "\("; similarly the character ")". Both were escaped. This can be changed to "[(]" and "[)]" as shown in the example below.
  
   var patt = /^[(][0-9]{3}[)][0-9]{3}-[0-9]{3}$/;
  patt.test("(123)456-678");  // true


   Equivalent PHP statement would be as shown below :
  
   $patt = "/^\([0-9]{3}\)[0-9]{3}-[0-9]{3}$/";
  echo preg_match($patt,"(234)234-456");  // 1
  $patt = "/^[(][0-9]{3}[)][0-9]{3}-[0-9]{3}$/";
  echo preg_match($patt,"(234)234-456");  // 1

  
2. Problem : Check whether a given location is in city_name, state format. Example : New York, NY
   

   Answer :
   var patt = /^(.*),\s[A-Z]{2}$/;
 patt.test("Saint George Island, AK"); // true
 patt.test("Saint George Island,AK");  // false, a space was expected after comma


3. Problem : Check whether a given email is in name@domain.com format.
   

    Email formats can be of various types. It is really difficult to build a small REGEX to catch right formatted email addresses. The domain names can be like gmail.com or yahoo.ac.in, or 1234.com. Email addess can be as complex as  !#$%&'*+-/=?^_`{}|~@example.org or "()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org or even " "@example.org. We would keep it to simple addresses like john.smith@dert.com or john.smith@yahoo.ac.in which falls within most used email formats.
   

   Answer :
   var patt = /^[A-Za-z0-9]{1}([A-Za-z0-9_]*)(\.[A-Za-z0-9_]+)*[a-zA-Z0-9_]*@([A-Za-z0-9]+)([A-Za-z0-9_]*)(\.[A-Za-z0-9]+)+$/;
 patt.test("john.smith@edu.co.au");

   

   Explanation ::
   a. ^[A-Za-z0-9]{1} means the string should start with alphanumeric character only. No dot or underscore is allowed at the beginning of email address.
   b. ([A-Za-z0-9_]*) means, next any alphanumeric or underscore may occur
   c. (\.[A-Za-z0-9_]+)* means, next a sequence of dot(.) and a series of characters may occur. For example, in j.g.h@gmail.com, the [.g] and [.h] portions are matched by this pattern. a._a._@gmail.com is a valid address but a._a._.@gmail.com is invalid and the local part [part before @] can not end with a dot (.).
   d. @ means the string should have a '@' character.
   e. ([A-Za-z0-9]+) means, after '@', alphanumeric character should only appear immediately. No dot(.) or underscore should appear immediately after '@'. For example, abc@_23.com is not valid address as underscore has appeared immediately after @.
   f. ([A-Za-z0-9_]*) means, after that, any length of alphanumeric characters including underscore may appear.
   g. (\.[A-Za-z0-9]+)+ means, next, any series of dot (.) and characters i.e ".ac", ".in" etc may occur minimum 1 time.
  
   However, we did not put a check on the following points.
   i. Domain names must end with ".com",".biz",".me", ".org",".net" etc.
   ii. Complex email addresses like "()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org can not be tested with the pattern above.


Check the 1st part of this article here 
Check the 3rd part of this article here

Friday, March 22, 2013

Check stucture of any DB table in PHP

We can use two SQL commands to get the structure of any table as shown in the code below :

Command format :
1. EXPLAIN  table_name;
2. DESCRIBE table_name;

PHP Code :


<?php
// MySQL Connect
$con = mysql_connect("localhost","root","");


// Select DB
mysql_select_db("test_db", $con);


// RUN QUERY
$res = mysql_query("EXPLAIN employee");


// Fetch Data
while( $row = mysql_fetch_assoc($res))
{
  print_r($row);
}
?>


Output :
Array
(
    [Field] => fname
    [Type] => varchar(100)
    [Null] => NO
    [Key] =>
    [Default] =>
    [Extra] =>
)
Array
(
    [Field] => mname
    [Type] => varchar(100)
    [Null] => NO
    [Key] =>
    [Default] =>
    [Extra] =>
)

...

The above output clearly displays details of a table 'employee' within the DB 'test_db'. The  columns are 'fname', 'lname' and do on ... 

Thursday, March 21, 2013

Ajax Problem in IE

I am sharing an Ajax problem that I had faced earlier with IE. Check the following Javascript code out.

<script>
var site_url = "http://example.com/";
// A function which fetches content thru Ajax
function load_cities_for_state(statename, target_elem)
{
  jQuery.ajax({
        url:  site_url + "ajax.php",
        type: 'POST',
        data: "load_city_for_state=1&state_name=" + statename,
        success: function(response) 

        {
            jQuery('#'+target_elem).html(response);
        }
    });
}
//// Function ends here

</script> 

Very simple code; its purpose is to call ajax.php, get the response and place the response in a target element. Problem was it was not running on IE. Even though it ran perfectly on local Xampp installation, it severely failed when ran from an online server.

The problem was with the "url" parameter in the Ajax call, which has "http://" in it. This made the whole Ajax calling process fail. Probably IE assumes that it is a cross-domain ajax call.

Rewriting the function following way fixed this issue.

function load_cities_for_state(statename, target_elem)
{
  jQuery.ajax({
        url:  "ajax.php",
        type: 'POST',
        data: "load_city_for_state=1&state_name=" + statename,
        success: function(response) {
          jQuery('#'+target_elem).html(response);
        }
    });
}


But this won't be a solution when you use custom URL in your website i.e http://www.findpeople.com/state/CA/city/San_Jose. Calling "ajax.php" would mean the path of the said file is  http://www.findpeople.com/state/CA/city/San_Jose/ajax.php which is wrong. The solution to it would be to declare a <base> tag in the header of your website as shown in the line below.

<base href='http://www.findpeople.com/' />

Mentioning a base URL for all the pages of your site, calling "ajax.php" through Ajax would always give "http://www.findpeople.com/ajax.php" as server URL.

Tuesday, March 05, 2013

Default Parameters in PHP

Using default parameters with functions is same as using it in C++. Only difference is in the function declaration. In C++, you must define default values from right end. 

For example :

// Valid in C++
int test( int i , long j = 10) {}   


// Invalid in C++, you must start providing the default value from right end
int test( int i = 10, long j ) {}   



But in php, the second statement above is a valid function declaration but you need to call the function as shown below:

// Function Definition
function test( int i = 10, long j ) {}

// Valid call
test(2,4); 

// Invalid, will give "Missing argument 2 for test()"
test(1); 


The calling rules are same for both php and c++ function calls.

Another example :


// Function Declaration
function test($a = 4, $b, $c = 10) {}  


// $c gets 10 from default parameters
test(8,9);           


// Invalid call as Argument 2 is missing
test(9);