preg_match_all with (...)*

Posted on 2004-10-08
Medium Priority
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 800 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 200 total points
ID: 12265768
From http://php.net/manual/en/reference.pcre.pattern.syntax.php#regexp.reference.back-references (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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

589 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