Monday, November 4, 2013

Regular Expression in PHP

11/04/2013


In this post you learn that how to write the Regular Expression. Regular expression is the most important part in form validations and it is widely used for search, replace and web crawling systems. If you want to write a selector engine (used to find elements in a DOM), it should be possible with Regular Expressions. 



Basics of regular expression in following three parts.

PART 1

^     Start of string
$     End of string
.      Any single character
+     One or more character
\      Escape Special characters
?    Zero or more characters



<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

#Input exactly match with “abc” 
$A = /^abc$/;

#Input start with “abc”
$B = /^abc/;

#Input end with “abc”
$C = /abc$/;

#Input “abc” and one character allowed Eg. abcx
$D = /^abc.$/;

#Input  “abc” and more than one character allowed Eg. abcxy
$E = /^abc.+$/;

#Input exactly match with “abc.def”, cause (.) escaped
$F = /^abc\.def$/;

#Passes any characters followed or not by “abc” Eg. abcxyz12....
$G = /^abc.+?$/


?>




PART 2

[abc]               Should match any single of character
[^abc]             Should not match any single character
[a-zA-Z0-9]    Characters range lowercase a-z, uppercase A-Z and numbers
[a-z-._]            Match against character range lowercase a-z and ._- special chats 
(.*?)                 Capture everything enclosed with brackets 
(com|info)       Input should be “com” or “info”
{2}                    Exactly two characters
{2,3}                 Minimum 2 characters and Maximum 3 characters
{2,}                   More than 2 characters

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

#URL validation:

var URL = /^(http|https|ftp):\/\/(www+\.)?[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.([a-zA-Z]{2,3})\/?/;
URL.test(“http://4evertutorials.blogspot.com”); // pass
URL.test(“http://www.4evertutorials.blogspot.com”); // pass
URL.test(“https://4evertutorials.blogspot.com/”); // pass

?>

PART 3

\d is short form of [0-9]  Any numbers
\D is short form of [^0-9] Any non-digits
\w is short form of [a-zA-Z0-9_] Characters,numbers and underscore
\W is short form of [^a-zA-Z0-9_] Except any characters, numbers and underscore
\s White space character
\S Non white space character


helpful? Share this

The Editorial Team of 4everTutorials consists of a group of PHP Professionals.

0 comments:

 

© 2014 4everTutorials. All rights resevered.

Back To Top