preg_match_all with (...)*

Posted on 2004-10-08
Last Modified: 2008-03-06
When I use preg_match_all to get repeated items, such as:

preg_match_all('/([A-Z]{3})(-([A-Z]{2})-([A-Z]{3}))*/', $myinput, $results);

it overwrites the results each time it iterates through the (...)* section.  How can I preserve these, so that when I input a string like "AAA-BB-CCC-DD-EEE" it will give me out items AAA, BB, CCC, DD, EEE?  Right now, it just gives me out AAA, DD, and EEE.

Thanks for any help.
Question by:jimstar
LVL 48

Accepted Solution

hernst42 earned 200 total points
ID: 12265331
preg_match_all can not do what you want.

It matches the whole string AAA-BB-CCC-DD-EEE.
$result[0][0] contains it. What you have to do with the result is:
$parts = explode('-', $result[0][0]);
The $parts contain whatyou want.

the subpaterns ( ) only hold the last matched items, not all possible matches
LVL 10

Assisted Solution

eeBlueShadow earned 50 total points
ID: 12265768
From (the paragraph above the BACK REFERENCES heading):

> When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration. For example,
> after (tweedle[dume]{3}\s*)+ has matched "tweedledum tweedledee" the value of the captured substring is "tweedledee".

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Introduction This article is intended for those who are new to PHP error handling (  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question