php - 如何将 '\\\' 替换为 '\' ?

标签 php regex

我的代码不起作用?而且我不想使用 str_replace ,因为要替换的斜线可能多于 3 个。我如何使用 preg_replace 完成这项工作?
我的代码是这样的:

<?php

$str='<li>
                <span class=\"highlight\">Color</span>
                Can\\\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
                Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
            </li>';
$str=preg_replace("@\\+@","\\",$str);
echo $str;

enter image description here

最佳答案

其他答案都有其优点,但对我来说,您实际想要完成的事情似乎截然不同。在 php 代码中,\\\' 不是三个斜杠后跟一个撇号,而是一个转义斜杠后跟一个转义撇号,在呈现的输出中,这正是您所看到的 — 一个斜杠后跟一个转义撇号撇号(无需在呈现的 html 中转义它们)。意识到转义符实际上不是字符串的一部分很重要;它只是一种帮助您表示通常在 php 中具有非常不同含义的字符的方法——在这种情况下,撇号通常终止字符串文字。在 php 中看起来像 4 个字符的字符串实际上只有 2 个字符。

如果这是您的代码的范围,则不需要字符串操作或正则表达式。你真正需要的只是这个:

<?php
$str='<li>
                <span class="highlight">Color</span>
                Can\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
                Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
            </li>';
echo $str;
?>

此处的撇号只需要一个转义字符,在呈现的 HTML 中您将看不到任何斜杠。

进一步阅读:

关于php - 如何将 '\\\' 替换为 '\' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17538511/

相关文章:

php - 从数据库中选择时的隐藏字段更改

php - Cakephp:使用一个命令字段将多个记录添加到单个模型

php - 如何通过hyperlink-url提交参数并在php中检索它们?

python - 使用 findall 捕获组?

php - 查询结果在 PHP/HTML 显示中显示不需要的 SQL SUM 公式文本

PHP readdir() : 3 is not a valid Directory resource

java - 如何在 Java 中通过正则表达式删除 &lt;script&gt;..&lt;/script&gt;?

java - 是否可以同时使用 $all 和 $regex ?

javascript - 从 url 中删除 guid 字符串

regex - 使用否定字符类在内部如何工作(无需回溯)?