Common use of the Regular Expression :
The common use of regular expression is the data validation . For Example , regular expression can be used to check the email address entered in to the form that contains the @ symbol and period (.) which are definitely part of the email address, without which the email address is not the email address at all.
Uses :
- Data entry form Validation .
- Verifying the input format , for example , format of email address.
- Parsing the data from pre-defined variables.
- Searching for and replacing the file data or database (when required) .
- if PHP code spec is being used to create user-defined functions to validate or manipulate portion of a string , than the user defined functions could be scrapped and regular expressions used instead.
- If the written function are being used : To make sure form data contains the valid information such as @ and (.) dot in the email address. –OR– To Loop through each character in string and replace it, if it matches a certain criteria , such as if if it’s upper case or if it is space .
PHP supports the two flavours of regular expressions .
1. Perl compact-able Regular Expressions (PERC) :
It is generally considered as bit faster , performance wise , than POSIX .
Example :
<?php
function emailValidate($email)
{
$emailSymbol = strpos($email , “@”);
$emailDots = strpos($email , “.”);
if( $emailSymbol && $emailDots )
{
return true ;
}
else
{
return false ;
}
}
echo emailValidate(php@evernews.online);
?>
2. POSIX Extended Regular Expressions :
POSIX is easier to grasp . the basic concept are same for the both types
Example :
<?php
function emailValidate($email)
{
return ereg(“^[a-zA-Z]+@[a-zA-Z]+.[a-zA-Z]+$ ” , $email);
}
echo emailValidate(php@evernews.online);
?>
Note : The first function looks easy and well structured , but it would be easier to to validate email address using one-line i.e is second example ,In the second example above uses the regular expression and contain one call ereg function.
The ereg function always return true or false , weather the string parameter matched in the regular expression or not .