【问题标题】:What is the best way to put this expression inside this set of quotes?将此表达式放在这组引号中的最佳方法是什么?
【发布时间】:2012-08-22 04:31:22
【问题描述】:

这个表达式最好的表达方式是什么:

echo isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : ''

在这个参数里面:

<?php
    echo "
    <input type='text' value=' *INSERT EXPRESSION* ' />
    ";
?>

我不确定处理引号内引号的最佳方法是什么,因此不胜感激。我知道可以通过更改整体语法来避免这种情况,但是,鉴于这些限制,我怎样才能最好地做到这一点?谢谢你的帮助!

【问题讨论】:

  • 当您使用单引号属性值时,您需要设置ENT_QUOTES 标志以使' 也被编码。

标签: php quotes ternary-operator


【解决方案1】:

最简单的方法...

<?php
    $exp = isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : '';

    echo "<input type='text' value=' $exp ' />";
?>

【讨论】:

    【解决方案2】:

    也许是这样的?

    <?php
        echo "
        <input type='text' value='" . 
            (isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : '') . 
        "' />";
    ?>
    

    【讨论】:

      【解决方案3】:

      这里有几种方法:

      方法一:

      <?php
          $expression = isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : '';
      
          echo "
          <input type='text' value='$expression' />
          ";
      ?>
      

      方法二:

      <?php
          $expression = isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : '';
      
          echo "
          <input type='text' value='" . $expression . "' />
          ";
      ?>
      

      方法三:

      <?php
          echo "
          <input type='text' value='" . isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : '' . "' />
          ";
      ?>
      

      更新:
      方法 4:我会使用方法 4 或 5,因为 PHP 处理起来更快。这里的变化是我使用单引号而不是双引号。

      <?php
          echo '
          <input type="text" value="' . isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : '' . '" />
          ';
      ?>
      

      方法五:

      <?php
          $expression = isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : '';
      
          echo '
          <input type="text" value="' . $expression . '" />
          ';
      ?>
      

      【讨论】:

      • 您刚刚复制了两个答案并粘贴为新答案.. :) 干得好.. :)
      • 你们在我的回答中击败了我 :(
      【解决方案4】:

      我总是使用printf()

      <?php
      
          printf("\n<input type='text' value='%s' />\n", isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : '');
      
      ?>
      

      【讨论】:

        【解决方案5】:

        试试这个,

        <?php
            define('URL',isset($GLOBALS['_url']) ? htmlspecialchars($GLOBALS['_url']) : '');
            echo "<input type='text' value=' ".URL." ' />";
        ?>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-09-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-18
          • 1970-01-01
          相关资源
          最近更新 更多