0

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: pattern matching an array, not their elements per se

Thanks

4

2 に答える 2

1

X((a),?)*X正規表現は文字列全体に一致するため、単一の一致がグループ化されます。最後((a),?)はグループ化されます。

一致させたいのは、aそのX前 (および文字列の先頭)、コンマの前、またはX前 (および文字列の末尾) を持つ です。

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

出力:

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

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

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

        )

)
于 2009-11-25T22:25:25.167 に答える
0

正規表現に X が含まれている場合、1 回一致します。その中のグループを含む 1 つの大きな一致が見つかります。あなたが望むのは、それぞれが独自の位置を持つ多くの一致です。

したがって、私の意見では、X を指定せずに /a/ または /a,?/ を検索するのが最善の方法です。この場合、matches[0] には 'a' のすべての出現が含まれます。

X の間にそれらが必要な場合は、文字列のこの部分を事前に選択します。

于 2009-11-25T22:24:30.233 に答える