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.
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.
You can split a string by backslash using a. split('\\') .
Try using the escaped character '\\' instead of '\' : String[] breakApart = sentence. Split('\\');
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.
$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.
You would use explode()
and escape the escape character (\
).
$str = 'HORSE\COW';
$parts = explode('\\', $str);
var_dump($parts);
CodePad.
array(2) {
[0]=>
string(5) "HORSE"
[1]=>
string(3) "COW"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With