我的代码不起作用?而且我不想使用 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;
最佳答案
其他答案都有其优点,但对我来说,您实际想要完成的事情似乎截然不同。在 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/