【问题标题】:In php, a string concatenation (with a string obtained by a function call) is disordered. Why?在php中,字符串连接(与函数调用获得的字符串)是无序的。为什么?
【发布时间】:2012-09-12 11:45:57
【问题描述】:

这个:

echo '<br>';
$author_single = sprintf( '/%s/single.php', 'francadaval' );
echo ( $author_single );

echo '<br>';
$author_single = sprintf( '/%s/single.php', the_author_meta( 'nickname') );
echo ( $author_single );

echo '<br>';
$nick = the_author_meta( 'nickname');
$author_single = sprintf( '/%s/single.php', $nick );
echo ( $author_single );

显示这个:

/francadaval/single.php
francadaval//single.php
francadaval//single.php

我看到连接顺序受函数调用影响,所以我尝试使用中间变量,但它不起作用。

使用点运算符代替 sprintf 或使用 "/{$nick}/single.php" 也是如此。

函数the_author_meta 是一个Wordpress 函数,用于从帖子作者那里获取数据,在这种情况下必须返回作者的昵称('francadaval')。

如何使用作者昵称的函数调用使$author_single 结果为“/francadaval/single.php”?

谢谢。

【问题讨论】:

  • 我不完全同意你的输出sprintf 不会删除输出前面的/
  • @Baba: sprintf 没有删除/。请阅读下面的答案以获得解释。

标签: php string wordpress concatenation


【解决方案1】:

您应该使用get_the_author_meta 而不是the_author_meta

  • the_author_meta 显示作者元
  • get_the_author_meta返回作者元

【讨论】:

    【解决方案2】:

    the_author_meta() 函数似乎不是返回值,而是输出值。

    所以实际发生的事情是这样的:

    echo '<br>';
    $author_single = sprintf( '/%s/single.php', 'francadaval' );
    echo ( $author_single );
    

    按预期输出/francadaval/single.php

    echo '<br>';
    $author_single = sprintf( '/%s/single.php', the_author_meta( 'nickname') );
    echo ( $author_single );
    

    内部函数the_author_meta首先运行,所以输出francadaval并返回null。然后sprintfnull 作为第二个参数运行,返回//single.php。然后echo 语句将//single.php 附加到输出(现在已经有francadaval)产生结果: francadaval//single.php

    echo '<br>';
    $nick = the_author_meta( 'nickname');
    $author_single = sprintf( '/%s/single.php', $nick );
    echo ( $author_single );
    

    与上述场景类似,您只是将函数调用拆分为单独的行。

    正如 soju 所说,在这种情况下使用的正确函数是 get_the_author_meta(),它会按预期返回值。

    所以正确的代码是:

    echo '<br>';
    $author_single = sprintf( '/%s/single.php', get_the_author_meta( 'nickname') );
    echo ( $author_single );
    

    【讨论】:

      猜你喜欢
      • 2015-05-05
      • 2014-11-20
      • 2020-12-18
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多