Thursday, July 19, 2012

Email validation using Regular Expression

Following code shows how to validate email in php.

<?php // chek email validation
if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$_POST['email']))
{
echo "invalid Email Address";
}
?>

Detect url contains query string ?

parse_url function is used to break the url components
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
  • scheme - e.g. http
  • host
  • port
  • user
  • pass
  • path
  • query - after the question mark ?
  • fragment - after the hashmark #


The following code reads url query string and convert into array.

<?php
$queries= parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY);

 // splits url query string into array
$queries_elements = split('&', $queries);
//converts to array
for($i = 0; $i != sizeof($queries_elements); $i++)
    {
    $queries = split('=', $queries_elements[$i]);
    //assigns to new array
    $params[$queries[0]]=$queries[1];
    }
var_dump($params);

?> 

More examples 
echo parse_url('http://example.com?mode=edit&id=34', PHP_URL_QUERY);
Output : 'mode=edit&id=34'
echo parse_url('http://example.com?mode=edit&id=34#user', PHP_URL_FRAGMENT)
Output : 'user'
echo parse_url('http://example.com', PHP_URL_SCHEME);
Output : 'http'
echo parse_url('http://example.com?mode=edit&id=34#user', PHP_URL_HOST);
Output : 'example.com'
echo parse_url('http://example.com:88?id=34', PHP_URL_PORT);
Output : 88