Skip to main content

How Regular Expression works in PHP?

Regular Expression, commonly known as RegEx is considered to be one of the most complex concepts. However, this is not really true. Unless you have worked with regular expressions before, when you look at a regular expression containing a sequence of special characters like /, $, ^, \, ?, *, etc., in combination with alphanumeric characters, you might think it a mess. RegEx is a kind of language and if you have learnt its symbols and understood their meaning, you would find it as the most useful tool in hand to solve many complex problems related to text searches and validations.

Basic Syntax of Regular Expressions

First of all, let's take a look at two special symbols: '^' and '$'. What they do is indicate the start and the end of a string, respectively, like this:
  • "^The": matches any string that starts with "The";
  • "of despair$": matches a string that ends in the substring "of despair";
  • "^abc$": a string that starts and ends with "abc" -- that could only be "abc" itself!
  • "notice": a string that has the text "notice" in it.
You can see that if you don't use either of the two characters we mentioned, as in the last example, you're saying that the pattern may occur anywhere inside the string -- you're not "hooking" it to any of the edges.

Multiple Characters

There are also the symbols '*', '+', and '?', which denote the number of times a character or a sequence of characters may occur. What they mean is: "zero or more", "one or more", and "zero or one." Here are some examples:

  • "ab*": matches a string that has an a followed by zero or more b's ("a", "ab", "abbb", etc.);
  • "ab+": same, but there's at least one b ("ab", "abbb", etc.);
  • "ab?": there might be a b or not;
  • "a?b+$": a possible a followed by one or more b's ending a string.
You can also use bounds, which come inside braces and indicate ranges in the number of occurences:
  • "ab{2}": matches a string that has an a followed by exactly two b's ("abb");
  • "ab{2,}": there are at least two b's ("abb", "abbbb", etc.);
  • "ab{3,5}": from three to five b's ("abbb", "abbbb", or "abbbbb").
Note that you must always specify the first number of a range (i.e, "{0,2}", not "{,2}"). Also, as you might have noticed, the symbols '*', '+', and '?' have the same effect as using the bounds "{0,}", "{1,}", and "{0,1}", respectively.
Now, to quantify a sequence of characters, put them inside parentheses:
  • "a(bc)*": matches a string that has an a followed by zero or more copies of the sequence "bc";
  • "a(bc){1,5}": one through five copies of "bc."

OR operator

The '|' symbol works as an OR operator: "tips|tutorials": matches a string that has either "tips" or "tutorials" in it.
"(b|cd)ef": a string that has either "bef" or "cdef".
"(a|b)*c": a string that has a sequence of alternating a's and b's ending in a c.


Wild character

A period ('.') is a wild character - it can stand for any single character:
"t.*p": matches a string that has a t followed by any number of characters followed by a p ("tip", "tp", "tdfsadfsadsfp", etc).
"^.{5}$": a string with exactly 5 characters ("bingo", "blind", "rainy", "asdfe", etc).

Bracket expressions

Bracket expressions lets you match a whole range of characters to a single position of a string:
"[tu]": matches a string that has either a 't' or a 'u' (that's the same as "t|u");
"[a-d]": a string that has lowercase letters 'a' through 'd' (that's equal to "a|b|c|d" and even "[abcd]");
"^[a-zA-Z]": a string that starts with a letter;
"[0-9]%": a string that has a single digit before a percent sign;
",[a-zA-Z0-9]$": a string that ends in a comma followed by an alphanumeric character.
Note that inside brackets, all the regex special characters are just ordinary characters - they don't do any of their usual regular expression functions.


Excluding characters

You can also exclude characters by using a '^' as the first symbol in a bracket expression:
"%[^a-zA-Z]%" matches a string with a character that is not a letter between two percent signs).
Note - the difference between this application and using ^ at the start of a regular expression which specifies the first character of a string.

Escaping regular expression characters

What do you do if you want to check for one of the regular expression special characters "^.[$()|*+?{\" in your text string? You have to escape these characters with a backslash ('\').

"(https?:\/\/)" matches http:// or https://

Retrieving text using preg_match

If you want to check if the string matches the regular expression or not, use preg_match function
preg_match($pattern, $string);
It returns a value of 1 if there is a match to your regular expression, a value of 0 if no match. For example,  

function validate_URL($url){
    $pattern = "/^(https?:\/\/)?([a-z0-9-])+(.[a-z0-9-]+)*$/";
    return preg_match($pattern, $url);
}
$result = validate_URL('http://www.google.com');
print $result;
output : 1
Some more valid urls you can test using this function like:
https://www.google.com
www.google.com

http://dirtyhandsphp.blogspot.com
dirtyhandsphp.blogspot.com

 

Comments

Popular posts from this blog

Odoo: Qweb Templates Cache Issue

Hi Everyone, Today I was working on a hotel booking template in Odoo and changes made in the Qweb template(.xml) were not reflecting on updating module with odoo service restart. Tried few times without any success :(. Finally, I decided to delete the old template from Odoo backend and then update module again and it worked like a charm!! :) Steps to delete template from backend: Settings --> User Interface --> Views --> Search by template name Delete the used template. Although it's a small post, but I'm sure it will meet the purpose and help someone in the future. Thanks!!! Enjoy Programming!! :) Reference Links: =================================== https://www.odoo.com/forum/help-1/question/odoo-cache-and-updating-qweb-templates-84492

Odoo12/13: Add an extra action in the tree view action button

This post will help you to add an action window in Odoo. Odoo13: <act_window id="action_make_bank_payment"              name="Do Bank Payment"              res_model="account.ob.payment"              binding_model="account.move"              view_mode="form"              target="new"              binding_views="list,form"              domain="[('type','=', 'in_invoice')]"              groups="account.group_account_user" /> Odoo12: <act_window id="action_make_bank_payment"              name="Do Bank Payment"              res_model="account.ob.payment"             view_mode="tree,form"              domain="[('type','=', 'in_invoice')]"              groups="account.group_account_user" /> Thanks!!! Enjoy Programming!! :) Reference: https://www.odoo.com/es_

Odoo/OpenERP: one2one relational field example

one2one relational field is deprecated in OpenERP version>5 but you can achieve the same using many2one relational field. You can achieve it in following two ways : 1) using many2one field in both the objects ( http://tutorialopenerp.wordpress.com/2014/04/23/one2one/ ) 2)  using inheritance by deligation You can easily find the first solution with little search over internet so let's start with 2nd solution. Scenario :  I want to create a one2one relation between two objects of openerp hr.employee and hr.employee.medical.details What I should do  i. Add _inherits section in hr_employee class ii. Add field medical_detail_id in hr_employee class class hr_employee(osv.osv):     _name = 'hr.employee'     _inherits = {' hr.employee.medical.details ': "medical_detail_id"}     _inherit = 'hr.employee'         _columns = {              'emp_code':fields.char('Employee Code', si