2

My code:

$string="655:47 Text: 0 n\some more text here\t\2\r\3\tl\0\f0\\f1\\f2\\a0\0\a1\0\a2\255";
$a=explode("\\",$string);
var_dump($a);

While the output i get is:

array(7) {
  [0]=>
  string(33) "655:47 Text: 0 n"
  [1]=>
  stringl20) "some more text
0"
  [2]=>
  string(2) "f1"
  [3]=>
  string(2) "f2"
  [4]=>
  string(3) "a0"
  [5]=>
  string(3) "a1"
  [6]=>
  string(3) "a2­"
}

I want to split the string on every '\' chat found ( and yet retain all the values) While I would like to have the function explode and to work correctly. How can I solve this ?

hakre
  • 193,403
  • 52
  • 435
  • 836
kritya
  • 3,312
  • 7
  • 43
  • 60

2 Answers2

3

Use single-quotes instead of double quotes,

$string='655:47 Text: 0 n\some more text here\t\2\r\3\tl\0\f0\\f1\\f2\\a0\0\a1\0\a2\255';
$a=explode('\',$string);
var_dump($a);

In php, if you use single quotes then special characters like '/t' etc loose their meanings and behave as plain strings.

sarveshseri
  • 13,738
  • 28
  • 47
1

It is working just fine. You just aren't seeing all of the non-printable characters.

It isn't entirely clear whether or not you intend to have characters like \n or \t in your message, but when used within double quotes ("), you are escaping into special characters. For example "\t" is a string that actually contains a tab character, and \n is a line feed.

If you don't want these characters, just change those double quotes to single quotes:

$string='655:47 Text: 0 n\some more text here\t\2\r\3\tl\0\f0\\f1\\f2\\a0\0\a1\0\a2\255';

If you do that, you'll get the following output:

array(17) {
  [0]=>
  string(16) "655:47 Text: 0 n"
  [1]=>
  string(19) "some more text here"
  [2]=>
  string(1) "t"
  [3]=>
  string(1) "2"
  [4]=>
  string(1) "r"
  [5]=>
  string(1) "3"
  [6]=>
  string(2) "tl"
  [7]=>
  string(1) "0"
  [8]=>
  string(2) "f0"
  [9]=>
  string(2) "f1"
  [10]=>
  string(2) "f2"
  [11]=>
  string(2) "a0"
  [12]=>
  string(1) "0"
  [13]=>
  string(2) "a1"
  [14]=>
  string(1) "0"
  [15]=>
  string(2) "a2"
  [16]=>
  string(3) "255"
}
Brad
  • 159,648
  • 54
  • 349
  • 530
  • I used to think that in php both quates are same :P – kritya May 06 '12 at 16:16
  • @kritya, In PHP, they definitely have two distinct meanings. In general, you should be using single quotes (`'`). They are slightly faster, since PHP doesn't try to parse variables and what not in your string. See also: http://stackoverflow.com/q/3446216/362536 – Brad May 06 '12 at 16:19