1

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.

user451555
  • 185
  • 2
  • 11
  • Try `(?:\ASections:|\G(?!\A))\s+(\w+);?`. See https://regex101.com/r/2sTJwE/1 – revo May 17 '18 at 18:46
  • This is tricky because what if you have multiple _Sections_ you want to have data separated. Otherwise, it's just a non-delineated list. If that's ok, I'd suggest a safer regex `(?:(?!\A)\G\s*;|Sections:\s*)[BCDE]\d+(?=\s*;)` –  May 17 '18 at 19:17

2 Answers2

3

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
)
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • Thanks! I read a lot of information about regular expressions, but I see the first time \K and \G. Can you tell where there is a full guide to regular expressions? – user451555 May 17 '18 at 19:03
  • @user451555 See [`\K` reference here](https://www.regular-expressions.info/keep.html) and [`\G` reference here](https://www.regular-expressions.info/continue.html). Basically, there are two comprehensive regex reference sites, https://www.regular-expressions.info and http://rexegg.com, but you may also check [SO `regex` tag description page] and [What does this regex mean?](https://stackoverflow.com/questions/22937618) for other nice resources. – Wiktor Stribiżew May 17 '18 at 19:40
0

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

Andreas
  • 24,301
  • 5
  • 27
  • 57