Free Article HomeSubmit Article l Contact Us


Mastering Regular Expressions in PHP 
What are Regular Expressions?

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 (http://php.net/preg_match). 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.


// Example string
$str = "Let's find the stuff in between these two previous brackets";

// Let's perform the regex
$do = preg_match("/(.*)<\/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 '
' . $matches['1'];
} else {
// No Match
echo "Couldn't find a match";
}

?>

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 (http://www.php.net/preg_match_all). 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 (http://www.php.net/preg_replace). 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.


// Example string
$str = "Let's replace the stuff between the bla brackets";

// Do the preg replace
$result = preg_replace ("/(.*)<\/bla>/", "new stuff", $str);

echo htmlentities($result);
?>

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:


// Example string
$str = "Let's replace the stuff between the bla brackets";

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

echo htmlentities($result);
?>

This would then print "Let's replace the new stuff (the old: stuff between) 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.

An Example

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:


// 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 '
';

// 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";
}

?>

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.

Another Example

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:


// 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 '
';

// And check the bad number
if (preg_match("/\d{3}-\d{7}/", $bad)) {
echo "Valid number";
} else {
echo "Invalid number";
}

?>

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.

What exactly is possible with Regular Expressions?

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 (http://www.codeproject.com/dotnet/RegexTutorial.asp)

Regular-Expressions.info (http://www.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 dennis@nocertainty.com

 
30 Most Recent Articles :
A Disputed New Business:Virtual Property Exchange

In many ways, the in-game economy is similar to a real world economy - goods and services are traded to mutual advantage and are mediated in currencies(gold,platinum,credit,etc.). An online broker, who goes by the screen name Rolala, was not a fan of online games until his 15-year-old son be[ Read Article]

THE UNITED STATES, A Terrorist Nation

I love the United States of America, but I cannot tolerate the UNITED STATES OF AMERICA. No I am not shouting at you, I am simply making a distinction, a difference that thirty-seven states of the union have noticed and moved to rectify. You see, AMERICA isn’t America anymore, nor does it in anyw[ Read Article]

Dollars and Sense

When I speak of the Federal Reserve and the fiat monetary system that controls our lives I feel as though my words are falling on deaf ears. I have the sense that the simplest conversations suggesting that change must be made invoke fear and condemnation from my fellow citizens. When will we tak[ Read Article]

Constitutionality

Is the 16th Amendment constitutional? Of course it is, the Supreme Court has made that as clear as it did the issue of slavery. But let us remember that it took the lives of more than 365,000 brave American men and the destruction of the Republic to wrest the matter from the courts and resolve the[ Read Article]

Five Secrets to Effective Pay-Per-Click Advertising

With so many companies swarming the World Wide Web with their products, how can you and your products and services stand out? Your ready answer would most likely be effective marketing. But how? How can you catch the eye of a surfer skimming carelessly through web pages? How can you keep the at[ Read Article]

How to Sell Bonds

If you want to make good money with banks, or any institution, Government and agency bonds are where it is at. Simply because all Government bonds and agencies are AAA rated, and banks can buy millions of dollars of any bond without incurring any credit risk. All banks own bonds of some sort, a[ Read Article]

Closing in the Car Business

The “P” Word. Closing is all about helping car customers make positive decisions. It is not about pressure or manipulation. Your customers need help overcoming the “P” word. Procrastination! Procrastination is natural when it comes to making a buying decision. Your customer is trying to avoid [ Read Article]

If You Build It They Will Come, or Will They?

All right, so you invested your time and energy to build your organization a great new web site, but you are not getting quite the results you were hoping for. Few customers are visiting or interacting with you and rarely do you get prospects to contact you through the site. So what can you do to [ Read Article]

Confessions of a Yoga Teacher

The following are questions that Yoga teachers still need to answer, despite overwhelming evidence that Yoga is ?the mother of all health maintenance systems.? Mainstream thought is finally catching up, with the progress Yoga is making, but it has taken 5,000 years for us to get this far. Serio[ Read Article]

Vertical Creep in Search Results :: Should Organic Optimizers be Concerned?

I thought for this week I’d give a summary of some of the more interesting Search Engine Strategies sessions which are currently going on in New York City. I was at SES as a speaker last year in New York and I have to say, there is a wealth of information there even if some of it is contradict[ Read Article]

How to build link popularity fast and free

We all knew that back link or link popularity is a big factor to get good position in any search engines. But building link popularity some times really hard if you don't know how to do it. One of the hardest problem for new webmasters is to get back link to their newly stablis[ Read Article]

Does Chiropractic Care Really Make Sense?

The Role of Chiropractic in Treatment Beyond the Resolution of Symptoms Do you have the same nagging injury that never seems to go away? Are you suffering needlessly with pain? Are you fed up with taking painkillers? Do you want to find out what is causing your pain? If your answer is ‘ye[ Read Article]

The Economic Implications of Buying Drugs Online

Although the Internet is fairly new (at least to the mainstream) online shopping has grown by leaps and bounds. Now you can buy almost anything you need, from food to fishing equipment, right through your computer. Of course, this has meant that commerce has been forced to adapt to the changing co[ Read Article]

Manning and Manning-Can Either Brother Win the Big One?

It was just over a year ago, after the Colts lost to the Pats in their post-season contest, that Boomer Esiason said on national television, "I think maybe Peyton (Manning) is this generation's Dan Marino." Esiason went on to state that Manning "is a great football player, but he's not going to get[ Read Article]

Branding, Branding, Branding - MSN fails to keep it Straight

Sometimes you see promotions come along and you wonder: did they just do that? The current MSN promotion called msnsearchandwin is a prime example of this. Not only do they use “black hat” or at least “questionable” tactics on the site, but the messaging is inconsistent. In this article [ Read Article]

The New MSN Search Interface :: A positive change or the antithesis of transformation?

Now, instead of wide blue bars there are sleek silver-grey bars. Also, the top bar where the search box is became narrower. To me this makes the page seem less “closed in” and more visually appealing. I now feel as if I can trust the results more because they have more room. I’ve also noti[ Read Article]

Malta Holidays

With Malta visitor numbers static in recent years and facing new competiton from former Eastern Bloc countries offering cheap holidays, the recent announcement by the Maltese government that negotiations were at an advanced stage with two low cost airlines has[ Read Article]

Drug Rehab Treatment Centers as an Experience, not a Punishment

Choosing a drug rehab treatment center is a decision that calls for both negative and positive emotions. Nobody wants addiction to overtake their life to the point that rehab is the necessary step. However, the decision to go to one is something to look forward to, as it is the decision to rebui[ Read Article]

Some ways to improve your king content

There are thousands of articles, books and forum posts which showed that content is king in search engine optimization (SEO). In this article, you can find some ways that can help you improve this king content for your web site. * Content for people first, not for search engines - Some webmaste[ Read Article]

Aerosmith Just Keeps On Rockin’

For over three decades, Aerosmith have been one of rock's most revered and popular bands, crafting classic songs full of raw guitar runs and intensely energetic vocals. The band first reached fame in the 1970’s with a string of hits including "Dream On," "Sweet Emotion" and "Walk This Way." During t[ Read Article]

Chicago Cubs Pitcher Mark Prior Re-signs

After many trips through the rumor mill, Mark Prior accepted the Chicago Cubs’ offer on January 27 to a one-year, $3.65 million contract. That is $900,000 more than the salary he would have earned under the contract he voided in November. Since Prior's definitive season in 2003 (18-6), he has cooled[ Read Article]

Social Networking - The Next Great Marketing Medium?

There has been a virtual explosion of social networking sites in the past couple of years. Even the big players like Google, Yahoo and MSN are getting into it. With so much interest in how social networks work, one begins to wonder if there is marketing potential within these social network[ Read Article]

How to choose paid directory for web site listing?

How to choose paid directory for web site listing? Search Engines are the major source of traffic for any website. High search engine ranking can boost number of your visitors and in turn leads to increase in sales. The best way to get top search engine placement is to improve link popularity [ Read Article]

Addiction Treatment Centers Using Experiential Therapies

Life is experience. Substance dependence overtakes a person’s ability to make her own decisions to experience life, and life is no longer actively participated in. Therefore, in overcoming addiction, it is vital to learn to re-experience life. This lesson helps a treatment center resident reint[ Read Article]

The DH: Making Life Tough for AL Pitchers

In 1973 Major League Baseball instituted three rules designed to lessen the power of pitchers and create more offense. One theory at work was that the game needed to be energized and that more hitting would create additional runs and excitement. Both the National and American Leagues lowered th[ Read Article]

Vacation on the Beach the Smart Way

Vacation on the Beach the Smart Way Almost everyone agrees; there is no more relaxing way to vacation than to take it to the beach. For the vacationer/traveler who hasn't considered a beach house rental before, they represent an affordable and fun family oriented alternative. There is an intell[ Read Article]

Malta Holidays and Hotels Buzzed by New Jets

With Malta visitor numbers static in recent years and facing new competiton from former Eastern Bloc countries offering cheap holidays, the recent announcement by the Maltese government that negotiations were at an advanced stage with two low cost airlines has sparked hopes that the island will see [ Read Article]

The Rising Cost of Prescription Drugs

If you’re like many Americans, the rising cost of prescription drugs may be costing you your health. In particular, seniors living on a fixed income with no insurance are finding it difficult to pay for necessary prescriptions out-of-pocket, and as a result, may be failing to receive the treatment[ Read Article]

Who's Tops in Hockey and Who's Not

The National Hockey League needs to do more to encourage better coverage of the hockey games. With so many other sports realizing national coverage, the NHL is sometimes forgotten. However, this year, there's a race for the Stanley Cup, and only one is set to win it. But which team will that be? [ Read Article]

The Danger Of Rounding Up Your Debts

Rounding up your debts is one of the biggest dangers to your financial position. It's also one of the easiest ways for your debts to get out of control. This way of thinking is best summed up by the following comment; ‘I already owe $27500 so what’s another $500. It takes my debt to a nice round [ Read Article]

 

World Top Stories :
Rep. Dennis Kucinich: 'Wake up America!'
Dennis Kucinich, the Ohio representative and two-time presidential candidate, roused the Democratic National Convention tonight with a fiery speech with the refrain: "Wake up America!" Later, Sen. Hillary Clinton planned to urge her supporters to rally behind Sen. Barack Obama. <p><a href="http://feeds.feedburner.com/~a/rss/cnn_topstories?a=jpRcKY"><img src="http://feeds.feedburner.com/~a/rss/cnn_topstories?i=jpRcKY" border="0"></img></a></p><div class="feedflare"> <a href="http://feeds.feedburner.com/~f/rss/cnn_topstories?a=gzSZdK"><img src="http://feeds.feedburner.com/~f/rss/cnn_topstories?i=gzSZdK" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/rss/cnn_topstories?a=UuZ6tK"><img src="http://feeds.feedburner.com/~f/rss/cnn_topstories?i=UuZ6tK" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/rss/cnn_topstories?a=MS1Fkk"><img src="http://feeds.feedburner.com/~f/rss/cnn_topstories?i=MS1Fkk" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/rss/cnn_topstories?a=KnfDzK"><img src="http://feeds.feedburner.com/~f/rss/cnn_topstories?i=KnfDzK" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/rss/cnn_topstories?a=1s3mPk"><img src="http://feeds.feedburner.com/~f/rss/cnn_topstories?i=1s3mPk" border="0"></img></a> </div><img src="http://feeds.feedburner.com/~r/rss/cnn_topstories/~4/375664709" height="1" width="1"/>


 

Copyright © 2006 Realook.com All Rights Reserved.