【问题标题】:echo a form input with backslashes使用反斜杠回显表单输入
【发布时间】:2014-07-07 11:41:27
【问题描述】:

尝试使用 echo 让 html 代码正常工作,

这可以作为 html:

<input type="text" name="ordernum" value="<?= isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '' ?>" />

但是当我用反斜杠转义值时(我尝试了几十种组合并且在 stackoverflow 上阅读了很多内容,但仍然无法修复它)我得到了意外的 T_STRING 错误。

echo ' <input type="text" name="ordernum" value=\'= isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '' \' />';

【问题讨论】:

  • 你不能在字符串文字的中间写任意的 PHP 代码。

标签: php forms input echo backslash


【解决方案1】:

作为Quentin has commented:

你不能只是在字符串中间写任意的 PHP 代码

这是因为 $_POST['ordernum'] 部分。

像这样重写它:

$val = isset($_POST["ordernumW]) ? htmlspecialchars($_POST["ordernum"]) : "";

echo "<input type='text' name='ordernum' value='$val' />";

【讨论】:

    【解决方案2】:

    您不能在字符串文字中使用 任意 代码。首先在一个变量中赋值,然后在echo 语句中使用该变量。

    $orderNum = isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '';
    echo ' <input type="text" name="ordernum" value="'.$orderNum.'" />';
    

    【讨论】:

    • 三元条件在字符串定义中完全有效。您应该只删除 &lt;?=?&gt; 标记并正确连接;-)
    • @user3556674 好的,接受这个答案并关闭这个问题。
    【解决方案3】:

    您需要使用\ 转义可能结束您的字符串的字符(即特别是字符串分隔符"')。

    这两行有效:

    echo "<input type=\"text\" name=\"ordernum\" value=\"" . (isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '') . "\" />";
    echo '<input type="text" name="ordernum" value="' . (isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '') . '" />';
    

    【讨论】:

    • 正如已经说过的here 你不能在字符串中使用任意条件
    • 此代码完全有效。三元条件计算为$_POST['ordernum'] 的HTML 转义版本或连接到第一部分的空字符串。您不能在字符串定义中使用if 语句,但没有什么可以阻止您连接文字、函数结果或三元条件。
    【解决方案4】:

    应该是这样的:

    echo('<input type="text" name="ordernum" value="'.(isset($_POST['ordernum'])?htmlspecialchars($_POST['ordernum']):'').'">');
    

    您使用句号来连接字符串,因此您应该结束字符串的第一部分,添加一个句号,然后是动态值,另一个句号,然后是字符串的其余部分。

    所以在你是字符串中,你做错了什么:

    value=\'= isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '' \'
    

    像这样:

    "first part of string".$myvariable."last part of string";
    

    你只需要对包含字符串的引号类型也进行转义:

    "I need to escape this \" but not this ' "
    'I need to escape this \' but not this " '
    

    【讨论】:

      【解决方案5】:
      $val = isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '';
      
      echo '<input type="text" name="ordernum" value="'. $val. '" />';
      

      【讨论】:

      • 这比三元if语句有什么好处?
      猜你喜欢
      • 1970-01-01
      • 2012-06-16
      • 2021-12-10
      • 2010-12-14
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多