0

我的字符串中有双反斜杠“\”,需要转换为单反斜杠“\”。我尝试了几种组合,当我使用 echo 或更多反斜杠意外添加到字符串时,最终整个字符串消失了。这个正则表达式让我发疯了……哈哈……

我在其他失败的尝试中尝试了这个:

$pattern = '[\\]';
$replacement = '/\/';

?>
<td width="100%">&nbsp;<?php echo preg_replace($pattern, $replacement,$q[$i]);?></td>

如果这是一个愚蠢的问题,我深表歉意,我感谢任何指示。

4

6 回答 6

7

使用stripslashes()- 它完全符合您的要求。

<td width="100%">&nbsp;<?php echo stripslashes($q[$i]);?></td>
于 2012-10-19T20:21:10.387 回答
2

使用 preg_replace 将双反斜杠转换为单反斜杠:

preg_replace('/\\\\{2}/', '\\', $str)
  • 就像 CodeAngry 说的那样,第一个参数中的\in 需要转义两次,一次 for string,一次 for 。regex
  • 在第二个参数中,它只为string.

说得通?

于 2014-11-09T01:55:32.970 回答
2

改用带斜杠。此外,在您的正则表达式中,您正在搜索单个反斜杠并且您的替换不正确。\\{2}应该搜索双反斜杠并\用单引号替换它们,尽管我还没有测试过。

只是为了进一步解释,该模式[\\]匹配由单个反斜杠组成的集合中的任何字符。在 php 中,您还应该用正斜杠分隔正则表达式:/[\\]/

您的替换 (没有分隔符)\不是匹配单个反斜杠的正则表达式。匹配单个反斜杠的正则表达式是\\. 注意转义。这就是说,替换术语需要是一个字符串,而不是一个正则表达式(反向引用除外)。

编辑:Sven 在下面声称 stripslashes 删除了所有反斜杠。这根本不是真的,我将在下面解释原因。

如果一个字符串包含 2 个反斜杠,第一个将被视为转义反斜杠并将被删除。这可以在http://www.phpfiddle.org/main/code/3yn-2ut看到。任何反斜杠本身都保留的事实与 stripslashes 删除所有反斜杠的说法相矛盾。

澄清一下,这个字符串声明是无效的:$x = "\";,因为反斜杠转义了第二个引号。此字符串"\\"包含一个反斜杠。在取消引用此字符串的过程中,此反斜杠将被删除。该"\\\\"字符串包含两个反斜杠。取消引用时,第一个将被视为转义反斜杠,并将被删除。

于 2012-10-19T20:22:38.340 回答
1

Never use a regular expression if the string you are looking for is constant, as is the case with "Every instance of double backslash".

Use str_replace() for this task. It is a very easy function that replaces every occurance of a string with another.

In your case: str_replace('\\\\', '\\', $var).

The double backslash actually translates into four backslashed, because inside any quotes (single or double), a single backslash is the start of an escape sequence for the following character. If you want one literal backslash, you have to write two of them. You want two backslashes, you have to write four of them.

I do not like the suggestion of stripslashes(). This will of course "decode" your double backslash into one single backslash. But it will also remove all single backslashes in the whole string. If there were none - fine, otherwise things will fail now.

于 2012-10-21T19:15:30.743 回答
0
$pattern = '[\\]'; // wrong
$pattern = '[\\\\]'; // right

将 \ 转义为 \\ 并将 \\ 转义为 \\\\ 因为 \\] 表示转义]。

于 2012-10-19T20:24:06.453 回答
-2

使用 htmlentities 函数将斜杠转换为 html 实体,然后使用 str_replace 或 preg_match 将它们更改为新实体

于 2012-10-19T20:32:05.007 回答