ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Mastering Regular Expressions in PHP

(Page 1 out of 4)

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.

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

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

Next: An Example »



Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. What are Regular Expressions?
  2. An Example
  3. Another Example
  4. What exactly is possible with Regular Expressions?
Bookmark Article
Download Article
PDF
Download this article as a PDF file