preg_split() and Regex - first array not being stored?

I have the following code in a while loop - the strings its parsing look like “Event 10 Men’s 800 Yard Run”. I want it to split the string after the event number, and have the event name below it. So like:
Event 10
Men’s 800 yard run

The problem is, $events[0] does not hold any information - $events[1] holds Men’s 800 Yard Run, but I cannot get it to store Event 10. Help please!

$events = preg_split("/Event\\x20[0-9]{2}/", $element, PREG_SPLIT_DELIM_CAPTURE);
echo $events[0]." <br /> ".$events[1]." <br />";

print_r($events) yields

Array ( [0] =>  [1] => Men's 800 Yard Run )

Perfect, thank you! My knowledge has now increased :slight_smile:

With PREG_SPLIT_DELIM_CAPTURE you need at least one “capturing group” (i.e. (…)) within the regular expression for it to be useful: it is this group which is returned as part of the split array. The simplest thing would be to wrap the whole thing in parentheses like /(Event\\x20[0-9]{2})/

Also, a few other thoughts; the PREG_SPLIT_DELIM_CAPTURE should be a fourth argument (you’re missing a limit, which defaults to -1; see the docs), also since you technically want to split after matching that Event <number> string then you could use some regex magic to specify exactly that (see below).


$events = preg_split("/Event [0-9]{2}\\K/", $element);
print_r($events);