Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a text by a backslash \ ?

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.

like image 311
user723220 Avatar asked Apr 25 '11 05:04

user723220


People also ask

How do you split a string on a backslash?

split() method to split a string on the backslashes, e.g. my_list = my_str. split('\\') . The str. split method will split the string on each occurrence of a backslash and will return a list containing the results.

How do you split a string with a backward slash in Python?

You can split a string by backslash using a. split('\\') .

What character is used to escape a backslash in a split string?

Try using the escaped character '\\' instead of '\' : String[] breakApart = sentence. Split('\\');

How do you split a backslash in JavaScript?

If you want to split the string by backslashes and spaces alike, the first step is to split by backslashes, done like this: step2 = str. split("\\"); Note that you have to escape the backslash here.


2 Answers

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

like image 54
Phoenix Avatar answered Sep 20 '22 19:09

Phoenix


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"
}
like image 36
alex Avatar answered Sep 21 '22 19:09

alex