tags:

views:

37

answers:

2

Hi

Consider the following example:

$target = 'Xa,a,aX';
$pattern = '/X((a),?)*X/';
$matches = array();
preg_match_all($pattern,$target,$matches,PREG_OFFSET_CAPTURE|PREG_PATTERN_ORDER);
var_dump($matches);

What it does is returning only the last 'a' in the series, but what I need is all the 'a's.

Particularly, I need the position of ALL EACH OF the 'a's inside the string separately, thus PREG_OFFSET_CAPTURE.

The example is much more complex, see the related question: http://stackoverflow.com/questions/1799419/pattern-matching-an-array-not-their-elements-per-se

Thanks

A: 

When your regex includes X, it matches once. It finds one large match with groups in it. What you want is many matches, each with its own position.

So, in my opinion the best you can do is simply search for /a/ or /a,?/ without any X. Then matches[0] will contain all appearances of 'a'

If you need them between X, pre-select this part of the string.

yu_sha
+1  A: 

It groups a single match since the regex X((a),?)*X matches the entire string. The last ((a),?) will be grouped.

What you want to match is an a that has an X before it (and the start of the string), has a comma ahead of it, or has an X ahead of it (and the end of the string).

$target = 'Xa,a,aX';
$pattern = '/(?<=^X)a|a(?=X$|,)/';
preg_match_all($pattern, $target, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => a
                    [1] => 1
                )

            [1] => Array
                (
                    [0] => a
                    [1] => 3
                )

            [2] => Array
                (
                    [0] => a
                    [1] => 5
                )

        )

)
Bart Kiers