tags:

views:

31

answers:

5
+1  Q: 

PHP regex query

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 ?

A: 

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.

Dan D.
+3  A: 

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.

Jens
+1  A: 

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.

Sarfraz
OP wants to know why what's being returned is empty and clearly indicates knowledge of `.` as a special character in the question.
Mark E
@Mark: You are right, updated.
Sarfraz
+5  A: 

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.

TNi
+2  A: 

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).

Gumbo