【问题标题】:PHP ternary operators error when concatenating string [duplicate]连接字符串时PHP三元运算符错误[重复]
【发布时间】:2019-11-18 20:13:20
【问题描述】:

我实际上是将这个 php 代码转换为分配给 var 的字符串,以便我可以在函数中返回它的值:

<?php if ($add_cta=='yes' ){?>
   <a class="button" href="<?php echo strip_tags(trim($a_href)); ?>">
     <?php echo strip_tags(trim($a_title)); ?>
   </a>
<?php } ?>

我已将以上内容转换为以下内容:

$html = '

($add_cta == "Yes" ? .
    ' < a class = "button" href = "'.strip_tags(trim($a_href)).
    '" > '.strip_tags(trim($a_title)).
    ' < /a>'. : "")
';

return $html;

但是出乎意料的'.'在线错误($add_cta == "Yes" ? .'

但这是连接字符串和 php 所必需的,对吧?我哪里错了

【问题讨论】:

  • 你用单引号打开它? PHP 不在单引号内执行 - 使用双引号,或者我更喜欢使用连接
  • 你确定要使用这么复杂的代码吗?你的代码不应该更具可读性以增强可维护性吗?
  • @NicoHaase - 我同意,我希望它被简化。但是有什么选择呢?我需要将标记存储为变量,以便在之后返回它的值
  • 这是一个完美的例子,使用if-statement 可以显着提高代码的可读性。仅仅因为你可以使用三元,并不意味着它是一个好主意。可读性非常很重要。
  • @Machavity 这不是您链接到的问题的副本。这有助于理解,但即使使用双引号也不是解决方案。字符串($add_cta == "Yes" ? ... 内的语句不会在任何引号内执行。

标签: php html ternary-operator shortcode


【解决方案1】:

您必须更正单引号的用法。尤其是第一个和最后一个单引号不是必需的。 PHP 不执行单引号内的任何代码。您可以使用双引号,但这只会打印变量并且与 HTML 结合使用会使事情变得更加复杂。以下代码使用了正确的单引号:

$html = ($add_cta == "Yes" ? .
    '<a class="button" href="'.strip_tags(trim($a_href)).'">'.
    strip_tags(trim($a_title)).
    '</a>'. : '');
return $html;

或者只使用if 声明:

$html = '';
if ($add_cta == "Yes")
{
    $href = strip_tags(trim($a_href));
    $title = strip_tags(trim($a_title));
    $html .= ' <a class="button" href="'.$href.'">'.$title.'</a>';
}
return $html;

【讨论】:

    【解决方案2】:

    我认为最简单/可读的方法是使用一个单独的模板来返回呈现的链接。

    链接模板.php

    <?php
    
    return '<a href="' . strip_tags(trim($a_href)) . '">' . strip_tags(trim($a_title)) . '</a>';
    

    您要使用此模板的方法/功能:

    return $add_cta === 'Yes' ? include 'link-template.php' : '';
    

    您应该考虑在包含模板之前定义$a_href$a_title

    【讨论】:

      【解决方案3】:

      试试这个。你犯了一些我已经修复的连接错误

      $a_href = "stackoverflow.com";
      $a_title = 'Anything';
      $html = 
      
      ($add_cta == "Yes" ? 
          ' < a class = "button" href = "'.strip_tags(trim($a_href)) .
          '" > '.strip_tags(trim($a_title)) .
          ' < /a>' : "")
      ;
      
      echo $html;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-09
        • 1970-01-01
        • 1970-01-01
        • 2010-11-21
        • 1970-01-01
        • 2020-06-10
        相关资源
        最近更新 更多