tags:

views:

32

answers:

3

I have a line of text that looks like "...X...Y...", where X and Y are both either Ok, Empty, or Open. Using PHP, I'm trying to use preg_match() to figure out what each one is.

$regex = '/(Ok|Open|Empty)/';
preg_match($regex, $match, $matches);
print_r($matches);

However, in the case that X is "Empty", and Y is "Ok", the following line gives me two matches: "Empty", and "Empty".

What's wrong with this regex?

Thanks!

+2  A: 

preg_match() do only one match, the first it find. In your case the first is "Empty".

The array returned by preg_match() contains the text matching to your whole regex in the first slot $matches[0]. For each group (the parenthesis) the next slots of $matches will contain the captured content. In your case you have one group, containing "Empty".

The result will be $matches[0] == "Empty" and $matches[1] == "Empty"


To capture everything that matches your regex you have to use the preg_match_all() method.

<?php

$match = "test Open test Empty test";

$regex = '/(Ok|Open|Empty)/';
preg_match_all($regex, $match, $matches);
print_r($matches);

?>

The first slot will contain all the matching strings, and the second will contain the first captured group for each of these strings.

The code on ideone


Resources :

Colin Hebert
A: 

use preg_match_all

knittl
A: 

You need to use preg_match_all() for multiple results. The typical matches-array is constructed like this:

array(
    'Empty', // whole match
    'Empty'  // match group 1
)

You are only matching the first Ok, Open or empty, but since you use a match group, it appears twice.

elusive