-1

I'm trying to use preg_split to split the following string at every space before a slash. I know it will be a simple REGEX but I can't seem to figure it out using RegExr?

$string = 'DZ9243/XSHAGT FFGD JERSE XS2 DZ9232/MHAGT SUUMTE KNI M10 DZ9232/LHAGT SUMMER KNI L6';

I need to split the string at the last space before every / to give the following result:

DZ9243/XSHAGT FFGD JERSE XS2 
DZ9232/MHAGT SUUMTE KNI M10
DZ9232/LHAGT SUMMER KNI L6

Any help would be appreciated!

lpw
  • 13
  • 4
  • You can use a lookahead assertion. Read the documentation of [regex patterns](http://php.net/manual/en/regexp.reference.assertions.php) – axiac Jan 17 '19 at 11:20

2 Answers2

0

In case it doesn’t have to be regex …

$string = 'DZ9243/XSHAGT FFGD JERSE XS2 DZ9232/MHAGT SUUMTE KNI M10 DZ9232/LHAGT SUMMER KNI L6';

$parts = explode(' ', $string);
$results = [];
$i = -1;

foreach($parts as $part) {
  strpos($part, '/') !== false ? $results[++$i] = $part : $results[$i] .= ' ' . $part;
}

var_dump($results);
misorude
  • 3,381
  • 2
  • 9
  • 16
0

You can use a lookahead assertion:

$string = 'DZ9243/XSHAGT FFGD JERSE XS2 DZ9232/MHAGT SUUMTE KNI M10 DZ9232/LHAGT SUMMER KNI L6';
$pieces = preg_split('@ (?=[^ ]*/)@', $string);

print_r($pieces);

The output is:

Array
(
    [0] => DZ9243/XSHAGT FFGD JERSE XS2
    [1] => DZ9232/MHAGT SUUMTE KNI M10
    [2] => DZ9232/LHAGT SUMMER KNI L6
)

The regex

@ (?=[^ ]*/)@
  • @ is the regex delimiter; usually / is used as delimiter but this regex attempts to match / and this is why it's better to use a different delimiter;
  • it is followed by a space character; it is the space you want to use as delimiter for splitting the input string;
  • ( starts a group; the group is needed by the assertion;
  • ?= is forward looking positive assertion; it requires the group to match the input string but it does not consume the characters from the input string that matches the group;
  • [^ ]*/ is the group content; it matches any non-space character any number of times, followed by a /; this is the word that contains the slash (/);
  • ) ends the group.

All in all, the regex matches the spaces that are followed by a word that contain a slash but the word is not consumed; it is not included in the delimiter by preg_split(), only the space character is used.

axiac
  • 68,258
  • 9
  • 99
  • 134