0

In PHP, when I run the following command:

$text = "";
$arr = preg_split('/,/', $text, PREG_SPLIT_NO_EMPTY);
print_r($arr);

I get the following array with a single empty element:

Array
(
    [0] => 
)

Yet, if I run it with -1 as the limit:

$text = "";
$arr = preg_split('/,/', $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);

I get a completely empty array:

Array
(
)

Why is this the case? According to the PHP manual -1 is the default value so I would expect the results to be the same in both cases.

2
  • Have you tried to count the characters with strlen() function? Commented Apr 18, 2016 at 6:23
  • PREG_SPLIT_NO_EMPTY If this flag is set, only non-empty pieces will be returned by preg_split(). so its giving onli non emty value so use another like "PREG_SPLIT_DELIM_CAPTURE" Commented Apr 18, 2016 at 6:26

1 Answer 1

5
preg_split($pattern , $subject [, int $limit = -1     [, int $flags = 0 ]] )
preg_split('/,/'    , $text     , PREG_SPLIT_NO_EMPTY                      );

The third parameter is the limit, PREG_SPLIT_NO_EMPTY == 1, when you pass PREG_SPLIT_NO_EMPTY as the third argument you're telling it the limit is 1 - you're not passing it in as a flag.

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

1 Comment

So in short: Passed the constant as wrong argument = Empty elements are allowed

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.