Free articles
Google
Web www.media13.com


Media13.com is a source of free to republish or reprint articles, writers may submit your articles in our database as long so you agree that your article will be freely republish or reprint by other.


Submit Article

Search our database

Received article from us.

Name

Email Address

Friends

Bollywood News
Link building
Article submission service
Freelance Writers
Laser hair removal

We have been looking for freelance writers. Contact us

 


Mastering Regular Expressions in PHP   by Dennis Pallett



<span style=`font-weight:bold; font-size: 1.2em`>What are Regular Expressions?</span>


A regular expression is a pattern that can match various text strings. Using regular expressions you can find (and replace) certain text patterns, for example `all the words that begin with the letter A` or `find only telephone numbers`. Regular expressions are often used in validation classes, because they are a really powerful tool to verify e-mail addresses, telephone numbers, street addresses, zip codes, and more.

In this tutorial I will show you how regular expressions work in PHP, and give you a short introduction on writing your own regular expressions. I will also give you several example regular expressions that are often used.


Regular Expressions in PHP


Using regex (regular expressions) is really easy in PHP, and there are several functions that exist to do regex finding and replacing. Let`s start with a simple regex find.

Have a look at the documentation of the preg_match function. As you can see from the documentation, preg_match is used to perform a regular expression. In this case no replacing is done, only a simple find. Copy the code below to give it a try.


<pre><?php

// Example string


$str = "Let`s find the stuff <bla>in between</bla> these two previous brackets";

// Let`s perform the regex


$do = preg_match("/<bla>(.*)</bla>/", $str, $matches);

// Check if regex was successful


if ($do = true) {


// Matched something, show the matched string


echo htmlentities($matches[`0`]);

// Also how the text in between the tags


echo `<br />` . $matches[`1`];


} else {


// No Match


echo "Couldn`t find a match";


}

?></pre>After having run the code, it`s probably a good idea if I do a quick run through the code. Basically, the whole core of the above code is the line that contains the preg_match. The first argument is your regex pattern. This is probably the most important. Later on in this tutorial, I will explain some basic regular expressions, but if you really want to learn regular expression then it`s best if you look on Google for specific regular expression examples.

The second argument is the subject string. I assume that needs no explaining. Finally, the third argument can be optional, but if you want to get the matched text, or the text in between something, it`s a good idea to use it (just like I used it in the example).


The preg_match function stops after it has found the first match. If you want to find ALL matches in a string, you need to use the preg_match_all function. That works pretty much the same, so there is no need to separately explain it.

Now that we`ve had finding, let`s do a find-and-replace, with the preg_replace function. The preg_replace function works pretty similar to the preg_match function, but instead there is another argument for the replacement string. Copy the code below, and run it.


<pre><?php

// Example string


$str = "Let`s replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace


$result = preg_replace ("/<bla>(.*)</bla>/", "<bla>new stuff</bla>", $str);

echo htmlentities($result);


?></pre>The result would then be the same string, except it would now say `new stuff` between the bla tags. This is of course just a simple example, and more advanced replacements can be done.

You can also use keys in the replacement string. Say you still want the text between the brackets, and just add something? You use the $1, $2, etc keys for those. For example:


<pre><?php

// Example string


$str = "Let`s replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace


$result = preg_replace ("/<bla>(.*)</bla>/", "<bla>new stuff (the old: $1)</bla>", $str);

echo htmlentities($result);


?></pre>This would then print `Let`s replace the <bla>new stuff (the old: stuff between)</bla> the bla brackets`. $2 is for the second `catch-all`, $3 for the third, etc.

That`s about it for regular expressions. It seems very difficult, but once you grasp it is extremely easy yet one of the most powerful tools when programming in PHP. I can`t count the number of times regex has saved me from hours of coding difficult text functions.

<span style=`font-weight:bold; font-size: 1.2em`>An Example</span>


What would a good tutorial be without some real examples? Let`s first have a look at a simple e-mail validation function. An e-mail address must start with letters or numbers, then have a @, then a domain, ending with an extension. The regex for that would be something like this: ^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$

Let me quickly explain that regex. Basically, the first part says that it must all be letters or numbers. Then we get the @, and after that there should be letters and/or numbers again (the domain). Finally we check for a period, and then for an extension. The code to use this regex looks like this:


<pre><?php

// Good e-mail


$good = "john@example.com";

// Bad e-mail


$bad = "blabla@blabla";

// Let`s check the good e-mail


if (preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/", $good)) {


echo "Valid e-mail";


} else {


echo "Invalid e-mail";


}

echo `<br />`;

// And check the bad e-mail


if (preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/", $bad)) {


echo "Valid e-mail";


} else {


echo "Invalid e-mail";


}

?></pre>The result of this would be `Valid E-mail. Invalid E-mail`, of course. We have just checked if an e-mail address is valid. If you wrap the above code in a function, you`ve got yourself a e-mail validation function. Keep in mind though that the regex isn`t perfect: after all, it doesn`t check whether the extension is too long, does it? Because I want to keep this tutorial short, I won`t give the full fledged regex, but you can find it easily via Google.

<span style=`font-weight:bold; font-size: 1.2em`>Another Example</span>


Another great example would be a telephone number. Say you want to verify telephone numbers and make sure they were in the correct format. Let`s assume you want the numbers to be in the format of xxx-xxxxxxx. The code would look something like this:


<pre><?php

// Good number


$good = "123-4567890";

// Bad number


$bad = "45-3423423";

// Let`s check the good number


if (preg_match("/d{3}-d{7}/", $good)) {


echo "Valid number";


} else {


echo "Invalid number";


}

echo `<br />`;

// And check the bad number


if (preg_match("/d{3}-d{7}/", $bad)) {


echo "Valid number";


} else {


echo "Invalid number";


}

?></pre>The regex is fairly simple, because we use d. This basically means `match any digit` with the length behind it. In this example it first looks for 3 digits, then a `-` (hyphen) and finally 7 digits. Works perfectly, and does exactly what we want.

<span style=`font-weight:bold; font-size: 1.2em`>What exactly is possible with Regular Expressions?</span>


Regular expressions are actually one of the most powerful tools in PHP, or any other language for that matter (you can use it in your mod_rewrite rules as well!). There is so much you can do with regex, and we`ve only scratched the surface in this tutorial with some very basic examples.

If you really want to dig into regex I suggest you search on Google for more tutorials, and try to learn the regex syntax. It isn`t easy, and there`s quite a steep learning curve (in my opinion), but the best way to learn is to go through a lot of examples, and try to translate them in plain English. It really helps you learn the syntax.

In the future I will dedicate a complete article to strictly examples, including more advanced ones, without any explanation. But for now, I can only give you links to other tutorials:


The 30 Minute Regex Tutorial


Regular-Expressions.info

Author Info:

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.webdev-articles.com


Latest 20 articles

Why Should I Hire a Seattle Real Estate Attorney? In every real estate transaction there are a wide variety of legal issues that must be taken care of. Contracts should always be reviewed by an attorney who understands the nuances of real estate law. But there are also state specific State laws to contend with. A Seattle real estate lawyer deals with a large number of State legal issues related to acquiring, financing, developing, managing, co

California IT Professionals – In Need of California Class Action Attorneys! It is hard to miss the wave of California wage and hour litigation related to California IT professionals and Computer employee overtime that has been sweeping California recently. Even the largest software and computer companies have paid out millions of dollars to employees wrongfully classified as “exempt”, or in other words, not entitled to overtime. A layperson would believe that with pr

Protect Your Mental Health With A Payday Loan Just when you thought that things couldn’t get any worse, more banks went under. More countries are declaring economic crisis. It seems that the world’s financial problems are bound to get worse. Even if you do not have considerable investments in various banks, I am sure that you are feeling the stress that results from these economic upheavals. I sure am. I am just an average person, with a

Free Bulk SMS services People are getting very busy these days without having enough time to talk unless it is very important. Mobile SMS have supported this need to contemporary times as now people do not want to call and enter in the unproductive conversation before coming up to the actual issue. SMS provides you the benefit to come straight to the point and also saves money. What if you get this totally free?

HELP – I Have IRS Levy Problems! If IRS collection notices are ignored, the IRS is forced to collect from taxpayers by force. They do this with their dreaded IRS levy. By law, the IRS has the right to levy bank accounts (IRS bank levy), garnish your paychecks (IRS wage levy), or even seize your assets. But you do not have to let the IRS bully you or your family. There are ways to stop an IRS levy. The first step is to know the

Why Use Professional Tax Debt Help? Good IRS tax relief is hard to find and for people with complicated tax issues, it is an absolute necessity. But how do you know which tax reduction firm is the best one to try? How can you be sure you're going to get the tax debt help that you need? And why is it so vital to receive help from professionals? Settling Your IRS Tax Debt For Less When your IRS tax debt is spiraling out

IRS Settlement – Can You Really Settle Your IRS Tax Debt for Less? It's possible to settle your IRS tax debt, but it presents a challenge. Proving you can settle your tax debt for less is a daunting experience. You have to contend with pages of IRS paperwork rife with technical terms. Settling tax debt is indeed a reality and it can be done. However, there's a lot you need to know before you attempt to settle your IRS tax debt. Rebuking the Lies - The

IRS Tax Relief – The Most Popular IRS Tax Relief Solutions Tax law provides many solutions for resolving tax debt. But if you were to contact the IRS directly, they would only alert you to one solution, and that's paying the tax debt in full. Here are five popular IRS tax relief solutions you should know about to be more informed. IRS Tax Settlement It is possible to settle your IRS tax debt. But there are some pitfalls you need to know. Fi

Hire the California Labor Board or California Labor Law Attorneys - You Decide With a downturn in the economy, many employers are cutting back on payroll. Unfortunately, some employers are reducing payroll costs by violating the California overtime laws. When this occurs, employees have essentially two options to recover their California overtime pay: the California labor board, or hiring California labor law attorneys. Although the California Labor Board is a commonly

Hiring a Car At Bangalore - Is More of Necessity Than A Luxury Your sedan is probably the best materialistic thing that you own and while going to a new place, that is what you ought to miss the most but if you are going to Bangalore then you probably have a option of getting a replacement so that you don’t miss it all that most because it will be as comfortable and as obedient as your own car and the Bangalor

How to Choose a Car Rental Company in Bangalore Bangalore is a place that lists one of the best as far as infrastructure is considered in India as it is the IT hub of India and thus the roads to drive is atmost pleasure and thus if Bangalore is the destination that you are planning for next then the best way to move around is by hiring a car. To hire is car is very simple if it is in Bangalore because there are some very good car rental compani

Car Rental Companies in Bangalore If you are travelling to Bangalore and hiring a car is what worrying you then you can be relaxed because this is one service that you will easily get in Bangalore and that too at very affordable and economic prices. Basically there are really good car rental companies in Bangalore available for renting the cars and you can either book in advance or go there and hire a car for yourself. Also, you h

Tips to Hire a Car in Bangalore One thing that most of us agree is that the fact that the most comfortable way to move around at any place is by your own vehicle but what if you are going to a new place, it is not possible to carry your vehicle along with you and you actually cannot trust too much on the public transportation system and at such situation the best possible option is to hire a car for yourself, at some places it c

Hire a Car: Comfortable Way to explore Bangalore If you are out to a new place than the first thing that comes into your mind is a comfortable accommodation and then the second one on the priority list is a comfortable way to move around in the city and if Bangalore is your preferred location, than you’ll be having options for both of the facilities, but if we specifically speak about the second one that is moving comfortably than the best opti

Car Rental – A convenient mode of transport in Bangalore Bangalore, a place which probably is considered one of the best places in India as far as infrastructure is considered and reasons are many for that, one is because of the IT hub that it is and also because it is one of very good places if you are considering holidays and because of this very good facility provided for the people visiting Bangalore is that you have many options in case if you are

Rent a Car in Bangalore: Take the Right Decision In today’s world, time is money; the more you save it better it is for you. And in that case if you are going to another place where you are not too familiar with the surroundings, then instead of wasting time on travelling by locating and travelling by public transport is to hire a vehicle for yourself. This helps in many ways, one it saves on time and also it moves at your pace so you don’t have

Bangalore Car Rental: Save Your Time When you are at an unknown place or for that matter known place and time is your major factor of concern then, the best way to save on time is by having your own vehicle for conveyance. This gives you freedom to move at your own pace and wish. And for that matter if you are at a place like Bangalore where the roads are so beautiful that it is a sheer pleasure to travel through your own rented vehi

Best Package Tours to Kerala Kerala – God’s own country which means heaven for those who appreciate the real untouched, naïve beauty of nature and if you are one of those than consider Kerala as the option for you next holiday. Kerala gives an option to explore the nature to the fullest because it has all the places where you can explore the nature be it scenic beaches or the hill stations or the ethnic culture, just everythi

Kerala Tour: A Getaway from Regular Stress If you are tired of daily stress and meetings and looking for a getaway so that you snatch some time for yourself with your loved one’s than Kerala holidays is the perfect is the perfect thing for you. Its calmness and closeness to nature would give you that much needed peace of mind that you always wanted. Also along with enjoying the beauty of this scenic place on your holidays to Kerala you can

Kerala Tour Packages: Have A Look If holidays are on your mind, then Kerala is one option that you cannot choose to neglect. Because Kerala is one place that offers you all from calm and serene natural places to exciting sports to exotic beaches and also beautiful hill stations, everything provided at one place which is also known as god’s own country. And obviously such wide range of activities would make it a tough job to cover

Categories
Acne
Advertising
Advice
Aerobics-Cardio
Affiliate Programs
Alternative
Arts
Attraction
Auctions
Audio-Streaming
Autos
Awards
Babies-Toddler
Beauty
Blogging-RSS
Book-Marketing
Branding
Breast-Cervical-Ovarian-Cancer
Broadband-Internet
Build-Muscle
Business
Cancer
Careers-Employment
Casino-Gambling
CGI
Coaching
Coffee
College-University
Colon-Rectal-Cancer
Communications
Computers
Cooking-Tips
Copywriting
Crafts-Hobbies
Creativity
Credit
Cruising-Sailing
CSS
Currency-Trading
Customer-Service
Dating
Debt-Consolidation
Debt-Relief
DHTML
Diabetes
Direct Mail
Divorce
Domain Names
EBooks
ECommerce
Education
Elder-Care
Email-Marketing
Email Entertainment
Entrepreneurialism
Environment
Exercise
Ezine-Marketing
Ezine-Publishing
Family
Finance
Fishing
Fitness
Food
Free
Games
Gardening
Goal-Setting
Golf
Government
Grief-Loss
Hair-Loss
Happiness
Hardware
Health
Hobbies
Holidays
Home-Security
Homes
Home Business
Home Repair
HTML
Humanities
Humor
Innovation
Inspirational
Interior-Decorating
Internet-Marketing
Javascript
Kids And Teens
Landscaping-Gardening
Law
Leadership
Leases-Leasing
Legal
Leukemia
Link Popularity
Loans
Lung-Cancer
Lymphoma-Cancer
Management
Marketing
Marriage-Wedding
Martial-Arts
Medicine
Meditation
Men's-Issues
Metaphysical
MLM
Mobile-Cell-Phone
Mortgage-Refinance
Motivational
Multimedia
Music
Negotiation
Network-Marketing
Networking
News-and-Society
Newsletters
Nutrition
Off-Line Promotion
Online Business
Online Promotion
Organizing
Other
Outdoors
Page Rank
Parenting
Personal-Tech
Pets
Photography
Podcasting
Poetry
Politics
Positive-Attitude
PPC-Advertising
Presentation
Prostate-Cancer
Psychology
Public-Speaking
Publishing
Real-Estate
Recipes
Recreation
Reference
Relationships
Religion
Sales
Sales-Management
Sales-Teleselling
Sales-Training
Satellite-Radio
Satellite-TV
Scams
Science
Security
Self Help
Self Improvement
Sexuality
SE Optimization SE Positioning
SE Tactics
Shopping
Site-Promotion
Site Security
Skin-Cancer
Small-Business
Social Issues
Society
Software
Spam
Spirituality
Sports
Stocks-Mutual-Funds
Strategic-Planning
Stress-Management
Structured-Settlements
Success
Supplements
Taxes
Team-Building
Technology
Teleseminars
Time-Management
Traffic-Building
Traffic Analysis
Travel
Uterine-Cancer
Vacation-Rentals
Video-Conferencing
Video-Streaming
Viral Marketing
VOIP
Web-Development
Webmasters
Web Design
Web Hosting
Weight Loss
Wine-Spirits
Women
Writing
Yoga

Copyright © media13.Com  2005. All Rights Reserved.

Sources : SEO India - Internet web directory