问题
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:
$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:
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"
}
回答3:
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.
来源:https://stackoverflow.com/questions/5775418/split-a-text-by-a-backslash