无法让 strtr() 处理转换为文本的工作


Can not get strtr() to work with conversion to text

我写了一些代码来帮助我工作,这会将文本的字符串/斑点转换为可以用作元数据的东西。

我写了以下内容,但只还原作品...我对PHP很陌生,所以对我来说这令人困惑!

<?php
$text = $_POST['field'];
if(isset($_POST['convert'])){   
    $trans = array("&" => "&amp;", "'"" => "&quot;", "“" => "&quot;", "”" => "&quot;", "'" => "&apos;", "<" => "&lt;", ">" => "&gt;");
} else if(isset($_POST['revert'])){
    $trans = array("&amp;" => "&", "&quot;" => "'"", "&apos;" => "'", "&lt;" => "<", "&gt;" => ">");
}
?>
<!DOCTYPE HTML>
<html>
<head>
    <title>GentetCreations</title>
    <meta name="description" content="website description" />
    <meta name="keywords" content="website keywords, website keywords" />
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
    <div id="main">
        <?php include("inc/pageHead.php"); ?>
        <div id="site_content">
            <?php include("inc/side.php"); ?>
            <div id="content">
                <form method="POST" action="metaConvert.php" id="convertMeta">
                    <table>
                        <tr>
                            <td>
                                <textarea id="field" name="field" rows="20" cols="80" autofocus><?php echo strtr($text, $trans); ?></textarea>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <p style="padding-top: 15px">
                                    <input class="submit" name="convert" value="Convert" type="submit">
                                    <input class="submit" name="revert" value="Revert" type="submit">
                                </p>
                            </td>
                        </tr>
                    </table>
                </form>
            </div>
        </div>
        <?php include("inc/footer.php"); ?>
    </div>
</body>
</html>

我在我在这里创建的网站上有一个现场演示:www.gentetcreations.co.uk/metaConvert.php

您的代码实际上可以工作,但您必须对"未编码"文本进行 HTML 编码以"按原样"显示它。试试这个:

<?php echo htmlspecialchars(strtr($text, $trans)); ?>

htmlspecialchars(( 执行此转换