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/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 = {             ...

How to draw Dynamic Line or Timeseries Chart in Java using jfreechart library?

Today we are going to write a code to draw a dynamic timeseries-cum-line chart in java.   The only difference between simple and dynamic chart is that a dynamic event is used to create a new series and update the graph. In out example we are using timer which automatically calls a funtion after every 1/4 th second and graph is updated with random data. Let's try with the code : Note : I had tried my best to provide complete documentation along with code. If at any time anyone have any doubt or question please post in comments section. DynamicLineAndTimeSeriesChart.java import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.XYPlot; import...

pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]

Recently, I faced this error in our Docker-Container environment. All the necessary packages were already installed but still, I was facing this clueless error. I search a bit and after an hour and so I found the exact reason and solution for this error. To know more about this error in detail. Please follow this Github thread. https://github.com/mkleehammer/pyodbc/issues/610 https://github.com/mkleehammer/pyodbc/issues/610#issuecomment-587523802 Solution: It's because the   server's certificate has too weak a key. In case you are using Linux env directly/not the Docker one.  Just edited /etc/ssl/openssl.cnf and change these 2 lines. MinProtocol = TLSv1.0 CipherString = DEFAULT@SECLEVEL=1 In case you are also using a container, please add these three lines to your Docker file. RUN chmod +rwx /etc/ssl/openssl.cnf RUN sed -i ' s/TLSv1.2/TLSv1/g ' /etc/ssl/openssl.cnf RUN sed -i ' s/SECLEVEL=2/SECLEVEL=1/g ' /etc/ssl/openssl.cnf Thanks!! Enjoy Programming! Refer...