1

Consider the snippet:

var_dump(preg_split("/./", "A.B.C")); // split on anything as the dot has not been escaped

which produces the output:

array(6) {
  [0]=>
  string(0) ""
  [1]=>
  string(0) ""
  [2]=>
  string(0) ""
  [3]=>
  string(0) ""
  [4]=>
  string(0) ""
  [5]=>
  string(0) ""
}

Can anyone please explain how it works? Also I don't see A,B or C in the output!! Why ?

2
  • 1
    If you don’t need the capabilities of regular expressions, don’t use them. In you case you could use explode instead. Commented Jul 9, 2010 at 7:38
  • @Gumbo: I want to know why am I getting 6 empty strings. Commented Jul 9, 2010 at 7:39

5 Answers 5

4

Observe that preg_split does not return the separator. So, of course you are not getting anything since you are splitting on any separator. Instead, you are seeing the 6 empty strings in between the characters.

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

Comments

2

preg_split will split the input string at all occurrences that match the given regular expression and remove the match. In your case . matches any character (except line breaks). So your input string A.B.C will be splitted at each character giving you six parts where each part is an empty string.

If you want to have the matches to be part of the result, you can use either look-around assertions or set the PREG_SPLIT_DELIM_CAPTURE (depending on the result you want to have).

Comments

2

The dot is a special character in regex. use "/\./" instead.

You do not see A, B, and C in your results, since you are splitting on them. All you get is the empty space between letters.

Comments

1

The dot (.) is special character in regex, you need to escape that, you are looking for:

var_dump(preg_split("/\./", "A.B.C"));

Result:

array(3) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "C"
}

Update:

Your regex is splitting by any character so it splits by all five chars A.B.C including that dot, hence you retrieve empty values.

1 Comment

OP wants to know why what's being returned is empty and clearly indicates knowledge of . as a special character in the question.
-1

What you are looking for is

var_dump(preg_split("/\./", "A.B.C"));

"." is a special character for regex, which means "match anything." Therefore, it must be escaped.

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.