Pattern matching with PHP

Matching patterns in strings is important in just about all Web applications that deal with data. PHP has a large number of pattern matching functions and extensions, tightly integrated into the language itself. The easiest pattern in a string to match is a single character. This can be accomplished in PHP as follows:

Python vs. PHP: Choosing your next project's language

01 <?
02 $c = 'a';
03 $str = 'string with a';
04 $found = 0;
05 for($i=0;$i<strlen($str);$i++) {
06 if($str[$i] == $c) {
07 		$found = 1;
08 		break;
09 	 }
10 }
11 ?>

In this basic script, we loop through each character of $str, testing it against the character we are looking for, $c. If we find it, we set $found to true and break the loop.

Conveniently, PHP has a function which does exactly this. The following does the same:

01 <?
02 $found = (strpos($str,$c) === false ? 0 : 1);
03 ?>

The function strpos() searches for $c in $str. It returns the offset of the first occurrence of $c, or false if $c isn't found. Notice that we use '===' to ensure that false is being returned and not 0, which is the first character of $str.

Another common requirement is to find the portion of a string matching a number of characters. For example, say you wanted to read a string containing numeric data up until a non-numeric character appeared. Consider the following:

01 <?
02 $nums = "1234567890";
03 $str = "340872 * 10";
04 $numlen = strspn($str,$nums);
05 $numeric = substr($str,0,$numlen - 1);
06 ?>

The strspn() function runs through $str until it does not find a character in $nums. It returns the length of this segment. The script above stores the number in $numeric using substr() in conjunction with this data.

Advanced pattern matching

Widely used on UNIX systems and in many programming languages, regular expressions are probably the most sophisticated all-purpose textual pattern matching mechanisms. A regular expression is a script which denotes a pattern.

The most elementary regular expressions are 'literals', i.e., characters which are interpreted literally. Consider the following:

01 <?
02 $regs = array();
03 if(ereg("abc","a string with abc",$regs)) {
04 echo "Pattern matched: {$regs[0]}\n";
05 } else {
06 echo "No pattern matched\n";
07 }
08 ?>

The ereg() function matches patterns in the first argument within the string passed as the second argument. Matches for this type of pattern are stored in the array $regs, passed as the third argument.

This kind of pattern matching can easily be accomplished with the functions already covered; what those functions cannot do is match wild cards. Consider the following:

01 <?
02 $regs = array();
03 if(ereg("wildcard: (.)","The wildcard: x",$regs)) {
04 echo "The wildcard matched: {$regs[1]}\n";
05 } else {
06 echo "No pattern matched\n";
07 }
08 ?>

The pattern used this time is decidedly different. There are two distinct parts. The first, "wildcard: " (note the trailing space) are treated literally. The second part, "(.)", is used to match the character "x" in the string. The stop (".") matches any character except a newline. The parenthesis instructs ereg() to place the matched character (that is, the character matching ".") to be placed in $regs. The first matched parenthesis starts at $regs[1].

01 <?
02 $regs = array();
03 if(ereg("wildcard: (.)","The wildcard: x",$regs)) {
04 echo "The wildcard matched: {$regs[1]}\n";
05 } else {
06 echo "No pattern matched\n";
07 }
08 ?>

Pattern matching can be vastly enhanced. When an asterisk ("*") is appended to a pattern, the regular expression matches zero or more instances of that pattern. For example, a regular expression "abc*" will match "ab" (remember: zero or more instances), "abc", "abcc", "abccccc" and so on. Notice that "abc*" does not match zero or more instances of "abc", but only "ab" followed by zero or more instances of the character "c".

To match "abc" zero or more times, the regular expression would be: "(abc)*". In this case, "abc" is enclosed in parentheses and is treated as an "atom" or "single unit".

Join the newsletter!

Error: Please check your email address.
Rocket to Success - Your 10 Tips for Smarter ERP System Selection
Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Most Popular Reviews

Latest Articles

Resources

PCW Evaluation Team

Ben Ramsden

Sharp PN-40TC1 Huddle Board

Brainstorming, innovation, problem solving, and negotiation have all become much more productive and valuable if people can easily collaborate in real time with minimal friction.

Sarah Ieroianni

Brother QL-820NWB Professional Label Printer

The print quality also does not disappoint, it’s clear, bold, doesn’t smudge and the text is perfectly sized.

Ratchada Dunn

Sharp PN-40TC1 Huddle Board

The Huddle Board’s built in program; Sharp Touch Viewing software allows us to easily manipulate and edit our documents (jpegs and PDFs) all at the same time on the dashboard.

George Khoury

Sharp PN-40TC1 Huddle Board

The biggest perks for me would be that it comes with easy to use and comprehensive programs that make the collaboration process a whole lot more intuitive and organic

David Coyle

Brother PocketJet PJ-773 A4 Portable Thermal Printer

I rate the printer as a 5 out of 5 stars as it has been able to fit seamlessly into my busy and mobile lifestyle.

Kurt Hegetschweiler

Brother PocketJet PJ-773 A4 Portable Thermal Printer

It’s perfect for mobile workers. Just take it out — it’s small enough to sit anywhere — turn it on, load a sheet of paper, and start printing.

Featured Content

Product Launch Showcase

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?