str_replace() 没有按预期工作

str_replace() doesn't work as expected

我有这样的字符串:

$string = "somehting<br><br>";

当我这样尝试 str_replace() 时:

echo str_replace("<br>","<c>",$string);

输出字符串根本没有改变。

我尝试了什么:

echo mb_detect_encoding($string); // returns UTF-8
var_dump(strpos($string, "<br>")); // bool(false)

我以前用html dom node class编辑过字符串,现在我真的不知道哪里出了问题。

我已尝试使用真实字符串在 sandbox.onlinephpfunctions.com 上重现该问题,并且有效。

所以我无法重现问题。

它确实用 <c> 替换了 <br>。它只是显示为空白。如果你添加 htmlspecialchars() 你可以看到它确实被替换了。

<?php
$string = "somehting<br><br>";
$string = htmlspecialchars(str_replace("<br>","<c>",$string));

var_dump(strpos($string, htmlspecialchars("<c>"))); // int(9)

事实证明。您的字符串使用 html 实体编码。因此,您只需查看源代码或使用 highlight_string($yourString) 即可看到这一点,然后您将看到:&lt; 而不是 <

要解码回来只需使用 html_entity_decode()。例如:

$string = str_replace("<br>","<c>", html_entity_decode($string));
highlight_string($string);