php 用反斜杠 \ 分割文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5775418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:27:20  来源:igfitidea点击:

Split a text by a backslash \ ?

phpexplodepreg-split

提问by user723220

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.

我需要将 HORSE\COW 分成两个词并去掉反斜杠。

回答by Phoenix

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

这会给你一个数组,因为"HORSE\COW"它会给出$array[0] = "HORSE"$array[1] = "COW"。随着"HORSE\COW\CHICKEN"$array[2]将是"CHICKEN"

Since backslashes are the escape character, they must be escaped by another backslash.

由于反斜杠是转义字符,因此它们必须由另一个反斜杠转义。

回答by alex

You would use explode()and escape the escape character (\).

您将使用explode()和转义转义字符 ( \)。

$str = 'HORSE\COW';

$parts = explode('\', $str);

var_dump($parts);

CodePad.

键盘

Output

输出

array(2) {
  [0]=>
  string(5) "HORSE"
  [1]=>
  string(3) "COW"
}

回答by Blender

Just explode()it:

explode()这样:

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

反斜杠用于转义引号和表示特殊字符:

  • \nis a new line.
  • \tis 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.
  • \n是一条新线。
  • \t是制表符。
  • \"是一个引号。您必须对其进行转义,否则 PHP 会将其读取为字符串的结尾。
  • \'单引号也是如此。
  • \\是一个反斜杠。由于它用于逃避其他事物,因此您必须逃避它。有点奇怪。