Pages

Regular expression in PHP (part 1)

Tuesday, September 11, 2012
We deal with at least one form on almost every project. So we need to validate this form. You can do the validation with javascript on the client side. But we also need to validate on the server side because user can turn off the javascript.

To do the form validation on the server side, we need to understand about the regular expression.

Let's start with the simple example.
<?php
$string = "webinone";
echo preg_match("/in/", $string);
?>
The above code will echo 1 because the characters "in" are found in our string.
The below code will echo 0.
<?php
$string = "webinone";
echo preg_match("/ni/", $string); //output: 0

echo preg_match("/IN/", $string); //output: 0
?>

Metacharacters

caret ^

Start of the string
<?php
$string = 'webinone';
echo preg_match("/^we/", $string); //output: 1

echo preg_match("/^eb/", $string); //output: 0
?>
The caret has another usage. I will show you in a moment.

dollor $

End of the string
<?php
$string = 'webinone';
echo preg_match("/one$/", $string); //output: 1

echo preg_match("/noe$/", $string); //output: 0
?>

Character Class []

If you code like [aeiou], it will return 1 when our string has one of the vowel.
<?php
$string = 'big';
echo preg_match("/[aeiou]/", $string); //Output: 1

$string1 = 'baig';
echo preg_match("/[aoiu]/", $string1); //Output: 1

$string2 = 'bag';
echo preg_match("/b[aoiu]g/", $string2); //Output: 1

$string3 = 'beg';
echo preg_match("/b[aoiu]g/", $string3); //Output: 0

$string4 = 'baog';
echo preg_match("/b[aoiu]g/", $string4); //Output: 0
?>
We used the caret ^ for the meaning of the start of the string. But if you use the caret ^ within the [], it means NOT.
<?php
$string = 'webinone';
if(preg_match("/[^a]/",$string))
{
 echo 'String has no a.';
}
?>
By the way if you use the $ withing [], it is not the end of string. It just a simple dollar sign and contains no special meaning within it.

We can use the - for the range of character class. [a-f] is equal to [abcdef].
<?php
$string = 'webinone';
echo preg_match("/[a-z]/", $string); //Output: 1

$string1 = 'WebInOne';
echo preg_match("/[a-z]/", $string1); //Output: 1

$string2 = 'WEBINONE';
echo preg_match("/[a-z]/", $string2); //Output: 0

$string3 = '12345';
echo preg_match("/[a-zA-Z]/", $string3); //Output: 0

$string4 = '12345';
echo preg_match("/[^0-9]/", $string4); //Output: 0
?>

Dot .

Any single character except new line (n).
<?php
$string = 'one';
echo preg_match("/./", $string); //Output: 1

$string1 = 'one';
echo preg_match("/[.]/", $string1); //Output: 0

$string2 = 'one';
echo preg_match("/o.e/", $string2); //Output: 1

$string3 = 'ons';
echo preg_match("/o.e/", $string3); //Output: 0

$string4 = 'onne';
echo preg_match("/o.e/", $string4); //Output: 0

$string5 = "ore";
echo preg_match("/o.e/", $string5); //Output: 1

$string6 = "one";
echo preg_match("/o.e/", $string6); //Output: 0
?>
 

Asterix *

a* means 0 or more of a. We need to see the little complicate example to know its usage.
<?php
$string = "<html>";
echo preg_match("/<[A-Za-z][A-Za-z0-9]*>/", $string); //Output: 1

$string1 = "<b>";
echo preg_match("/<[A-Za-z][A-Za-z0-9]*>/", $string1); //Output: 1

$string2 = "<h3>";
echo preg_match("/<[A-Za-z][A-Za-z0-9]*>/", $string2); //Output: 1

$string3 = "<3>";
echo preg_match("/<[A-Za-z][A-Za-z0-9]*>/", $string3); //Output: 0
?>
In the above example we use <[A-Za-z][A-Za-z0-9]*>. In this regex, < and > are literal characters. The first character class matches a letter. The second character class matches a letter or digit. The star repeats the second character class. Because we used the star, it's OK if the second character class matches nothing. So our regex will match a tag like <B>. When matching <HTML>, the first character class will match H. The star will cause the second character class to be repeated three times, matching T, M and L with each step.

Plus +

a+ mean one or more of a.
<?php
$string = "php";
echo preg_match("/ph+p/", $string); //Output: 1

$string1 = "phhp";
echo preg_match("/ph+p/", $string1); //Output: 1

$string2 = "pp";
echo preg_match("/ph+p/", $string2); //Output: 0

$string3 = "12345";
echo preg_match("/[a-z]+/", $string3); //Output: 0
?>

Question mark ?

a? Zero or one of a.
<?php
$string = "123456";
echo preg_match("/123-?456/", $string); //Output: 1

$string1 = "123-456";
echo preg_match("/123-?456/", $string1); //Output: 1

$string2 = "123--456";
echo preg_match("/123-?456/", $string2); //Output: 0
?>

Curly braces {}

a{3} Exactly 3 of a
a{3,} 3 or more of a
a{,3} Up to 3 of a
a{3,6} 3 to 6 of a

<?php
$string = "google";
echo preg_match("/go{2}gle/", $string); //Output: 1

$string1 = "gooogle";
echo preg_match("/go{2}gle/", $string1); //Output: 0

$string2 = "gooogle";
echo preg_match("/go{2,}gle/", $string2); //Output: 1

$string3 = "google";
echo preg_match("/go{,2}gle/", $string3); //Output: 0

$string4 = "google";
echo preg_match("/go{2,3}gle/", $string4); //Output: 1
?>

Subpattern ()

<?php
$string = "This is PHP.";
echo preg_match("/^(This)/", $string); //Output: 1

$string1 = "That is PHP.";
echo preg_match("/^(This)/", $string1); //Output: 0

$string2 = "That is PHP.";
echo preg_match("/^([0-9])/", $string2); //Output: 0

$string3 = "7 is lucky number.";
echo preg_match("/^([0-9])/", $string3); //Output: 1
?>

Logical Or |


<?php
$string = "This is PHP.";
echo preg_match("/^(This|That)/", $string); //Output: 1

$string1 = "That is PHP.";
echo preg_match("/^(This|That)/", $string1); //Output: 1
?>

Backslash /

Where we use backslash?
If you want to use these eleven metacharacters ^+*.?$()|[ as literal characters in your regex, we need to escape them with a backslash.
<?php
$string = 'webinone.net';
if(preg_match("/./",$string))
{
 echo 'String has dot.';
}
$string1 = 'webinone+net';
if(preg_match("/+/",$string1))
{
 echo 'String has + sign.';
}
?>

Now let's try the real world example. Below example is to test for the email validation. It is not a prefect one, but it will validate most common email address formats correctly.

Crate a blank document in your favourite editor and paste following code in your document. And then save as mail_regex.php in your www (in wamp) folder.
<html>
<head>
 <title>Mail text</title>
</head>
<body>
<?php
 if(isset($_POST['submit']))
 {
  $email = $_POST['email'];
  if(preg_match("/^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/", $email))
  echo "Valid mail";
  else
  echo "Not Valid";
 }
?>
<form method="post" action="mail_regex.php">
 <input type="text" name="email" id="email" size="30" />
 <input name="submit" type="submit" value="Submit"/>
</form>
</body>
</html>

Our regex pattern for the email address is like below:
^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$
As you know, email address are always in a particular format:

username @ domain . extension

For our username part we use

^[a-zA-Z0-9._%-]+

^ means our username must start with this character class [a-zA-Z0-9._%-].
+ follow by the character class so you must enter one or more of the previous character class.

For our domain part we use

[a-zA-Z0-9.-]+

Our domain name must present one or more of that character class.

And then we need to escape with the backslash to use the . as the literal character.

For the extension part we use

[a-zA-Z]{2,4}$

So your extension must present 2 to 4 of the previous character class.

Now you can create some of the regex patterns by yourself I think.

There are many other regex patterns in PHP. I will explain you the rest of other regex patterns in the part 2.

Ref:

phpro.org

regular-expressions.info

53 comments:

  1. Thanks you for sharing the unique content. you have done a great job. I appreciate your effort and I hope that you will get more positive comments from the web users.

    Hadoop training in chennai

    ReplyDelete
  2. Great and really helpful article! Adding to the conversation, providing more information, or expressing a new point of view...Nice information and updates. Really i like it and everyday am visiting your site..
    Fleet Management Software

    ReplyDelete
  3. Amazing Article ! I have bookmarked this article page as i received good information from this. All the best for the upcoming articles. I will be waiting for your new articles. Thank You ! Kindly Visit Us @ Coimbatore Travels | Ooty Travels | Coimbatore Airport Taxi | Coimbatore taxi | Coimbatore Taxi

    ReplyDelete
  4. Thanks for your great and helpful presentation I like your good service.I always appreciate your post.That is very interesting I love reading and I am always searching for informative information like this.Well written article Thank You for Sharing with Us pmp training Chennai | pmp training centers in Chennai | pmp training institutes in Chennai | pmp training and certification in Chennai

    ReplyDelete
  5. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.
    apple iphone service center in chennai | imac service center in chennai | ipod service center in chennai | apple ipad service center in chennai | <a href="http://www.applerepairchennai.com/iphone7plus-service-center-in-chennai.html</a>

    ReplyDelete
  6. Superb blog I visit this blog it's extremely marvelous. Interestingly, in this blog content composed plainly and justifiable. The substance of data is exceptionally instructive.
    oracle fusion financials classroom training
    Workday HCM Online Training
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    Oracle Fusion HCM Classroom Training

    ReplyDelete
  7. Information from this blog is very useful for me, am very happy to read this blog Kindly visit us @ Luxury Watch Box | Shoe Box Manufacturer |  Candle Packaging Boxes | Wallet Box

    ReplyDelete
  8. When you buy a new HP printer, you try to connect it using the user manual. The manual provided by the 123.hp.com/setup manufacturer may not be in detail. Hence, our technical experts have given simple instructions that guide you through the HP Printer setup and troubleshooting issues if any. We also offer free 123hp driver (Both Basic and Full-feature) to make your printer function efficiently. The navigation is too easy such that all instructions are available on one single page. www.123.hp.com/setup

    ReplyDelete
  9. Quickbooks enterprise support Contact the Enterprise support team to resolve the QuickBooks Enterprise issues. To contact our certified QuickBooks + 1 (833) 400-1001 specialist, contact the Quick Books support team.

    ReplyDelete
  10. Thanks for the post you just made my day.

    data science course singapore is the best data science course

    ReplyDelete
  11. Buy Tramadol Online from the Leading online Tramadol dispensary. Buy Tramadol 50mg at cheap price Legally. Buying Tramadol Online is very simple and easy today. Shop Now.

    ReplyDelete
  12. Nice explanation of the topic
    Sanjary Kids is one of the best play school and preschool in Hyderabad,India. Give your child the best preschool experience by choosing the best playschool of Hyderabad in Abids. we provide programs like Play group,Nursery,Junior KG,Senior KG,and provides Teacher Training Program.
    pre and primary teacher training course in hyderabad

    ReplyDelete
  13. Get Tramadol Online from the Leading Tramadol online dispensary. Buy Tramadol 100 mg at lowest price Legally. Buy Tramadol Online is very simple and easy today.
    Buy Now.

    ReplyDelete
  14. Excellent topic provided by the author clearly

    Sanjary Academy is the best Piping Design institute in Hyderabad, Telangana. It is the best Piping design Course in India and we have offer professional Engineering Courses like Piping design Course, QA/QC Course, document controller course, Pressure Vessel Design Course, Welding Inspector Course, Quality Management Course and Safety Officer Course.
    best Piping Design Course
    piping design course with placement
    Piping Design Course
    Piping Design Course in Hyderabad ­
    Piping Design Course in India­
    best Piping Design institute
    best institute of Piping Design Course in India

    ReplyDelete
  15. Great blog posting information I liked it

    Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional Engineering Course like Piping Design Course,QA/QC Course,document Controller course,pressure Vessel Design Course,Welding Inspector Course, Quality Management Course, Safety officer course.
    Welding Inspector Course
    Safety officer course
    Quality Management Course
    Quality Management Course in India

    ReplyDelete
  16. Thank you so much for sharing the article.Really I get many valuable information from the article
    Modalert 200mg
    Buy Modalert online
    Buy Artvigil 150mg Online

    ReplyDelete
  17. Great Article! Thanks for sharing this types of article is very helpful for us! If you have any type of pain like chronic pain, back pain etc.
    Best Pharmacy Shop

    ReplyDelete
  18. Very Nice Blog!!! Thanks for Sharing Awesome Blog!! Prescription medicines are now easy to purchase. You can order here.
    Buy Soma 350mg
    Order soma online
    buy Ambien 5 mg online
    buy Ambien online
    buying Gabapentin COD
    Buy Gabapentin cod online

    ReplyDelete

  19. Thank you so much for the post it is A Very Useful For me. you can easily purchase Tramadol Online in usa click here Click here toBuy Ol Tram 100mg tablets

    ReplyDelete
  20. Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better! Cheers, keep doing awesome
    Maharaja Surajmal Brij University BCOM 1st, 2nd & Final Year Time Table 2020

    ReplyDelete
  21. Getting india visa is not a difficult work that people think

    ReplyDelete
  22. We develop free teaching aids for parents and educators to teach English to pre-school children. For more info please visit here: English for children

    ReplyDelete
  23. Struggling to rank on Google? Local Doncaster+ Sheffield firm with no contracts, Businesses we will Launch your SEO campaign instantly. Get results within months & increase you organic rankings. Know more- SEO sheffield

    ReplyDelete
  24. Thanks for sharing these wonderful designs, its helpful to

    ReplyDelete
  25. Thank you for this great work… for this article and very informative article. Wish to travel Visit turkey best place Mardin’s Old City is easily toured by walking Turkey apply for Trukish visa through e Turkish visa online application. The US visa for Turkey visitors need to fill online e visa application upload documents & photos, make online payment. Pakistan is a world's 26th largest economy City is easily toured by walking.they need to Pakistan business visa application and apply emergency visa to Pakistan. The process is so simple Just go to online emergency visa to Pakistan visa application form and fill out the Pakistan visa Information requirements application and UK all citizens traveling to Pakistan ,get the evisa.

    ReplyDelete
  26. Thank you for this great work… for this article and very informative article Mustache transplantation

    ReplyDelete
  27. www.amazon.com/mytv.: Are you facing problem to sign in amazon prime video in your tv? Just follow easy method to register amazon mytv enter code prime video on your TV or device.

    ReplyDelete
  28. Thanks for sharing such a awesome post. We are a leading online pharmacy in USA providing pain relief tablets anti anxiety medicine at cheap rates.

    Buy Xanax online USA
    Modalert 200mg tablets online USA
    Tapentadol tablet online USA
    Ambien 10 mg Tablet USA

    ReplyDelete
  29. This site helps to clear your all query.
    This is really worth reading. nice informative article.
    uniraj ba 3rd year result
    shekhauni ba final result

    ReplyDelete
  30. Thank you for sharing our information.

    Jewellery By Mitali Jain is the best website to buy artificial jewellery online and Jain Jewellery in Jaipur. They sell fancy and attractive products like Earrings, Rings, Necklaces, Headgears, Bracelets, Mask and Glass Chains, Bookmark Jewellery, Gift Cards and many more items like this. And also checkout our new collections Summer Luna Collection and Holy Mess Collection

    ReplyDelete
  31. Nice article thank you for this. Check the kenya online visa requirements before you apply for the Kenya visa through online visa application. The e visa application offers the fast visa services. Thank you

    ReplyDelete
  32. It was wondering if I could use this write-up on my other website, I will link it back to your website though. Great Thanks.

    BA time table | BCom Time Table | BSc Time Table.

    ReplyDelete
  33. It's such meaningful content. So nice words you are saying . I feel so glad to read it. I prefer that people read it once. It's really helpful and knowledgeable. I suggest to you If you want to know the India business visa requirements that is passport validity at least 6 months, 2 blank pages in passport, upload to copy of Business/invitation card. For more details check out the blue link.

    ReplyDelete