15

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.

1

3 Answers 3

45
$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.

2
  • I tried with \\ it simply returns the values HORSE\COW and "blank" as the two values.
    – user723220
    Commented Apr 25, 2011 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
    Commented Apr 25, 2011 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"
}
0
7

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.
8
  • I ran the code from above with \\ and get HORSE\COW and [0] as the array elements. Must be a bug.
    – user723220
    Commented Apr 25, 2011 at 16:45
  • Did you use $text = 'HORSE\COW'; or $text = "HORSE\COW";? The quotes matter.
    – Blender
    Commented Apr 25, 2011 at 16:46
  • I can confirm that the print_r(explode) example from above is working, however you forgot a ")" at the end.
    – user723220
    Commented Apr 25, 2011 at 16:53
  • Single quotes double quotes, same result. Text remains unexploded.
    – user723220
    Commented Apr 25, 2011 at 17:02
  • What PHP version are you using? This works perfectly: codepad.viper-7.com/IqKhfU
    – Blender
    Commented Apr 25, 2011 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.