Split a text by a backslash \ ?
Asked Answered
L

3

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.

Lengthwise answered 25/4, 2011 at 5:17 Comment(1)
php.net/manual/en/language.types.string.php - read the section that talks about escaping stringsLucubration
Y
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.

Yeorgi answered 25/4, 2011 at 5:20 Comment(2)
I tried with \\ it simply returns the values HORSE\COW and "blank" as the two values.Lengthwise
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"Yeorgi
C
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"
}
Concomitant answered 25/4, 2011 at 5:19 Comment(0)
M
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.
Microscopic answered 25/4, 2011 at 5:19 Comment(8)
I ran the code from above with \\ and get HORSE\COW and [0] as the array elements. Must be a bug.Lengthwise
Did you use $text = 'HORSE\COW'; or $text = "HORSE\COW";? The quotes matter.Microscopic
I can confirm that the print_r(explode) example from above is working, however you forgot a ")" at the end.Lengthwise
Single quotes double quotes, same result. Text remains unexploded.Lengthwise
What PHP version are you using? This works perfectly: codepad.viper-7.com/IqKhfUMicroscopic
Not worth it. I changed all of my text list data to have a "/" slash delimiter, explode now works.Lengthwise
The lesson here is don't build databases with \ and / (metacharacters) Use commas for crying out loud. Preg commands will haunt you in the night.Lengthwise
Lol, that's good. I've had that happen, but in my case I forgot a delimiter in the first place. It was all one big line...Microscopic

© 2022 - 2024 — McMap. All rights reserved.