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 PC World newsletter!

Error: Please check your email address.

Our Back to Business guide highlights the best products for you to boost your productivity at home, on the road, at the office, or in the classroom.

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

Gavin Sherry

PC World
Show Comments

Essentials

Microsoft L5V-00027 Sculpt Ergonomic Keyboard Desktop

Learn more >

Lexar® JumpDrive® S57 USB 3.0 flash drive

Learn more >

Mobile

Lexar® JumpDrive® S45 USB 3.0 flash drive 

Learn more >

Exec

Lexar® Professional 1800x microSDHC™/microSDXC™ UHS-II cards 

Learn more >

Lexar® JumpDrive® C20c USB Type-C flash drive 

Learn more >

Audio-Technica ATH-ANC70 Noise Cancelling Headphones

Learn more >

HD Pan/Tilt Wi-Fi Camera with Night Vision NC450

Learn more >

Budget

Back To Business Guide

Click for more ›

Most Popular Reviews

Latest News Articles

Resources

PCW Evaluation Team

Azadeh Williams

HP OfficeJet Pro 8730

A smarter way to print for busy small business owners, combining speedy printing with scanning and copying, making it easier to produce high quality documents and images at a touch of a button.

Andrew Grant

HP OfficeJet Pro 8730

I've had a multifunction printer in the office going on 10 years now. It was a neat bit of kit back in the day -- print, copy, scan, fax -- when printing over WiFi felt a bit like magic. It’s seen better days though and an upgrade’s well overdue. This HP OfficeJet Pro 8730 looks like it ticks all the same boxes: print, copy, scan, and fax. (Really? Does anyone fax anything any more? I guess it's good to know the facility’s there, just in case.) Printing over WiFi is more-or- less standard these days.

Ed Dawson

HP OfficeJet Pro 8730

As a freelance writer who is always on the go, I like my technology to be both efficient and effective so I can do my job well. The HP OfficeJet Pro 8730 Inkjet Printer ticks all the boxes in terms of form factor, performance and user interface.

Michael Hargreaves

Windows 10 for Business / Dell XPS 13

I’d happily recommend this touchscreen laptop and Windows 10 as a great way to get serious work done at a desk or on the road.

Aysha Strobbe

Windows 10 / HP Spectre x360

Ultimately, I think the Windows 10 environment is excellent for me as it caters for so many different uses. The inclusion of the Xbox app is also great for when you need some downtime too!

Mark Escubio

Windows 10 / Lenovo Yoga 910

For me, the Xbox Play Anywhere is a great new feature as it allows you to play your current Xbox games with higher resolutions and better graphics without forking out extra cash for another copy. Although available titles are still scarce, but I’m sure it will grow in time.

Featured Content

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?