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

Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World




very nice

Comments are now closed.

Latest News Articles

Most Popular Articles

Follow Us

GGG Evaluation Team

Kathy Cassidy


First impression on unpacking the Q702 test unit was the solid feel and clean, minimalist styling.

Anthony Grifoni


For work use, Microsoft Word and Excel programs pre-installed on the device are adequate for preparing short documents.

Steph Mundell


The Fujitsu LifeBook UH574 allowed for great mobility without being obnoxiously heavy or clunky. Its twelve hours of battery life did not disappoint.

Andrew Mitsi


The screen was particularly good. It is bright and visible from most angles, however heat is an issue, particularly around the Windows button on the front, and on the back where the battery housing is located.

Simon Harriott


My first impression after unboxing the Q702 is that it is a nice looking unit. Styling is somewhat minimalist but very effective. The tablet part, once detached, has a nice weight, and no buttons or switches are located in awkward or intrusive positions.


Best Deals on GoodGearGuide

Compare & Save

Deals powered by WhistleOut

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?