13

I've searched for hours. How can I separate a string by a "\"

I need to separate HORSE\COW into two words and lose the backslash.

Tony
  • 716
  • 4
  • 17
  • 34
user723220
  • 707
  • 3
  • 10
  • 19

3 Answers3

41
$array = explode("\\",$string);

This will give you an array, for "HORSE\COW" it will give $array[0] = "HORSE" and $array[1] = "COW". With "HORSE\COW\CHICKEN", $array[2] would be "CHICKEN"

Since backslashes are the escape character, they must be escaped by another backslash.

Phoenix
  • 4,328
  • 1
  • 18
  • 13
  • I tried with \\ it simply returns the values HORSE\COW and "blank" as the two values. – user723220 Apr 25 '11 at 16:09
  • Well, I assumed that the string was being pulled in from somewhere like a database, if not, the \ in the string must be escaped as well like: `"HORSE\\COW"` – Phoenix Apr 25 '11 at 17:44
8

You would use explode() and escape the escape character (\).

$str = 'HORSE\COW';

$parts = explode('\\', $str);

var_dump($parts);

CodePad.

Output

array(2) {
  [0]=>
  string(5) "HORSE"
  [1]=>
  string(3) "COW"
}
Community
  • 1
  • 1
alex
  • 438,662
  • 188
  • 837
  • 957
6

Just explode() it:

$text = 'foo\bar';

print_r(explode('\\', $text)); // You have to backslash your
                               // backslash. It's used for
                               // escaping things, so you
                               // have to be careful when
                               // using it in strings.

A backslash is used for escaping quotes and denoting special characters:

  • \n is a new line.
  • \t is a tab character.
  • \" is a quotation mark. You have to escape it, or PHP will read it as the end of a string.
  • \' same goes for a single quote.
  • \\ is a backslash. Since it's used for escaping other things, you have to escape it. Kinda odd.
Blender
  • 257,973
  • 46
  • 399
  • 459