0

Note: I recently asked this question but it turns out the solution I'm looking for is more advanced than I initially thought.

Using preg_split, how would I split this up, note that the string before the delimiters varies:

$string = "big red apple one purple grape some stuff then green apple yatta yatta red cherry green gape";

I want to use an array of strings as the delimiters and I want them to be included in the result. Deliminters: [apple, grape, cherry]

My desired output is:

Array("big red apple", "one purple grape", "some stuff then green apple", "yatta yatta red cherry", "green grape");

Here's what I had originally:

$string = "big red apple one purple grape some stuff then green apple yatta yatta red cherry green gape";
$matches = preg_split('(apple|grape|cherry)', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($matches);

It prints this: Array ( [0] => big red [1] => one purple [2] => some stuff then green [3] => yatta yatta red [4] => green gape )

without the delimiters.

johnpecan
  • 9
  • 4
  • Do you have any knowledge of ReGeX (pronounced _re-jek_)? Have you tried _anything_? – Cole Tobin Apr 30 '13 at 16:05
  • RTLM? http://php.net/manual/en/reference.pcre.pattern.syntax.php – Marc B Apr 30 '13 at 16:07
  • possible repost of http://stackoverflow.com/questions/16303206/preg-split-how-to-include-the-split-delimiter-in-results-when-using-an-array-of – mario Apr 30 '13 at 17:15

2 Answers2

3

If you fix the typo of the last word in your input string, then (one possible) pattern is:

~(?<=apple|grape|cherry)\s*~

This is using a look-behind and then splitting on the following whitespace (if it exists). So it also works on the end of the string.

Full example:

<?php
/**
 * preg_split using PREG_SPLIT_DELIM_CAPTURE with an array of delims
 * @link http://stackoverflow.com/a/16304338/2261774
 */

$string = "big red apple one purple grape some stuff then green apple yatta yatta red cherry green grape";

var_dump(
    preg_split("~(?<=apple|grape|cherry)\s*~", $string, -1, PREG_SPLIT_NO_EMPTY)
);

See it in action.

As you can see I am not using the PREG_SPLIT_DELIM_CAPTURE here because I want to have the spaces on which I split removed. Instead the PREG_SPLIT_NO_EMPTY flag is used so that I do not get the (empty) split at the end of the string.

M8R-1jmw5r
  • 4,896
  • 2
  • 18
  • 26
0

A bit simpler, with the same result:

$string = "big red apple one purple grape some stuff then green apple yatta yatta red cherry green grape";
$re='/\S.*?\s(?:apple|grape|cherry)/';
preg_match_all($re,$string,$m);
var_dump($m[0]);
Miguel
  • 11
  • 2