gpt4 book ai didi

php - sprintf 多次使用相同的值

转载 作者:可可西里 更新时间:2023-11-01 13:50:21 25 4
gpt4 key购买 nike

我试图在使用 sprintf 时在不同的地方使用相同的值,但失败了。

<?php

$score = 50;
$percent = 10;

$str = "Hello: You scored %s (%s%%). Your score is %2$s %%"; //Problem is here %2$s

echo sprintf($str,$score,$percent);
?>

我收到此错误:注意:C:\web\apache\htdocs\sprintf.php 中第 6 行的 undefined variable :s 警告:sprintf():C:\web\apache\中的参数太少htdocs\sprintf.php 第 8 行

最佳答案

使用单引号代替双引号:

$str = 'Hello: You scored %s (%s%%). Your score is %2$s %%';

变量在双引号内扩展,因此 $s 被视为变量,而不是格式化选项。

如果要使用双引号,可以转义美元符号:

$str = "Hello: You scored %s (%s%%). Your score is %2\$s %%";

关于php - sprintf 多次使用相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20261277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com