Reputation: 8879
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 ?
Upvotes: 1
Views: 97
Reputation: 382746
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.
Upvotes: 1
Reputation: 655319
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).
Upvotes: 2
Reputation: 16682
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.
Upvotes: 4
Reputation: 25563
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.
Upvotes: 2
Reputation: 1127
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.
Upvotes: -1