替换“<";以及“>";在PHP的字符串中


Replacing "<" and ">" in a string in PHP

我想创建一个打印源代码的链接,但我不知道为什么替换标记("<"answers">")不起作用,也不知道是否有解决这个问题的方法。

<?php
    $key = "";
    if(isset($_REQUEST["key"])){
    $key = $_REQUEST["key"];
}
$code = '
<html>
    <head>
    <meta charset="utf-8"/>
    <title>Test</title>
    <style>
        h1 {
            text-align: center;
        }
        h4 {
            text-align: left;
        }
    </style>
    </head>
    <body>
        <a href="?key=y"> <h1> Source code </h1> </a>
    </body>
</html>
    ';
    echo($code);
    if($key == "y"){
        str_replace("<", "&#60;", $code);
        str_replace(">", "&#62;", $code);
        echo("<h4>" . $code . "</h4>");
    }
?>

感谢您的帮助。

您不保存str_replace函数的结果

if($key == "y"){
    $code = str_replace(["<", ">"], ["&#60;", "&#62;"], $code);
}
  1. 正如Thamaijan已经说过的,你应该使用htmlentities,而不是手动替换这两个字符。

  2. 忽略#1,您的特定问题是由于没有将str_replace的结果分配到任何位置造成的。您需要$code = str_replace(......, $code);

$code = str_replace("<", "&lt;", $code);
$code = str_replace(">", "&gt;", $code);
 if($key == "y"){
        echo("<h4>" . htmlspecialchars($code) . "</h4>");        
    }