在php中,字符串连接(通过函数调用获得的字符串)是无序的。为什么?

时间:2012-09-12 11:45:57

标签: php string wordpress concatenation

此:

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'使用函数调用作为作者的昵称?

感谢。

2 个答案:

答案 0 :(得分:2)

您应该使用get_the_author_meta代替the_author_meta

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

答案 1 :(得分:1)

看来,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。然后以sprintf作为第二个参数运行null,返回//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 );
相关问题