user451555
user451555

Reputation: 308

PHP regexp how get all matches in preg_match

I have string

$s = 'Sections: B3; C2; D4';

and regexp

preg_match('/Sections(?:[:;][\s]([BCDE][\d]+))+/ui', $s, $m);

Result is

Array
(
    [0] => Sections: B3; C2; D4
    [1] => D4
)

How I can get array with all sections B3, C2, D4

I can't use preg_match_all('/[BCDE][\d]+)/ui', because searching strongly after Sections: word.

The number of elements (B3, С2...) can be any.

Upvotes: 1

Views: 128

Answers (2)

Andreas
Andreas

Reputation: 23958

You don't need regex an explode will do fine.
Remove "Section: " then explode the rest of the string.

$s = 'Sections: B3; C2; D4';

$s = str_replace('Sections: ', '', $s);
$arr = explode("; ", $s);

Var_dump($arr);

https://3v4l.org/PcrNK

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may use

'~(?:\G(?!^);|Sections:)\s*\K[BCDE]\d+~i'

See the regex demo

Details

  • (?:\G(?!^);|Sections:) - either the end of the previous match and a ; (\G(?!^);) or (|) a Sections: substring
  • \s* - 0 or more whitespace chars
  • \K - a match reset operator
  • [BCDE] - a char from the character set (due to i modifier, case insensitive)
  • \d+ - 1 or more digits.

See the PHP demo:

$s = "Sections: B3; C2; D4";
if (preg_match_all('~(?:\G(?!^);|Sections:)\s*\K[BCDE]\d+~i', $s, $m)) {
    print_r($m[0]);
}

Output:

Array
(
    [0] => B3
    [1] => C2
    [2] => D4
)

Upvotes: 3

Related Questions