0

I was trying to include the delimiter while using preg_split but was unsuccessful.

print_r(preg_split('/((?:fy)[.]+)/', 'fy13 eps fy14 rev', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));

I'm trying to return:

array(
    [0] => fy13 eps
    [1] => fy14 rev
)

With the flags parameter set to PREG_SPLIT_DELIM_CAPTURE:

If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.

The fy is in parenthesis, so I don't know why this doesn't work.

2 Answers 2

6

Your current approach isn't working because "parenthesized expression" here is referring to capturing groups, and the ?: to start your group makes it a non-capturing group. So you can get the fy included by changing your expression to /(fy)/, however I don't think this is what you want because you will get an array that contains fy, 13 eps, fy, and 14 eps (the parenthesized expressions are separate entries in the result).

Instead, try the following:

print_r(preg_split('/(?=fy)/', 'fy13 eps fy14 rev', -1, PREG_SPLIT_NO_EMPTY));

This uses a lookahead to split just before each occurrence of fy in your string.

Sign up to request clarification or add additional context in comments.

Comments

0

With the example you gave, I am not sure that you really need to use the preg_split function. For example you can obtain the same with preg_match_all in a more efficient way (from the perspective of performance):

preg_match_all('/fy(?>[^f]++|f++(?!y\d))*/', 'fy13 eps fy14 rev', $results);
print_r($results);

The idea here is to match fy followed by all characters but f one or more times or f not followed by y all zero or more times.

More informations about (?>..) and ++ respectively:

  1. here for atomic groups
  2. and here for possessive quantifiers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.