sprintf(PHP)return不需要的字符(×)

sprintf (PHP) return unwanted character (×)

我尝试了php中的sprintf函数,结果不尽如人意,添加一个不想要的字符:

https://localhost/item?item_id=abcd&redirect=https://www.google.com/×tamp=1616847526

不需要的是 ×

我预期的结果:

https://localhost/item?item_id=abcd&redirect=https://www.google.com/&timestamp=1616847657

这是我的代码。

public function generateUrl()
{
    $url = sprintf(
        '%s%s?item_id=%s&redirect=%s&timestamp=%s',
        'https://localhost',
        '/item',
        'abcd',
        'https://www.google.com/',
        $this->timestamp,
    );
    return $url;
}

如果我用其他内容替换 timestamp 字符串,结果会很好。 timestamp 怎么了?如何解决?

谢谢。

sprintf没有问题,&times是乘号x的HTML实体。

如果您确实需要像现在这样显示生成的 URL,您可以使用 return htmlentities($url) 而不是直接返回 $url,或者通过更改 sprintf 呼叫:

$url = sprintf(
        '%s%s?item_id=%s&redirect=%s&timestamp=%s',
        'https://localhost',
        '/item',
        'abcd',
        'https://www.google.com/',
        $this->timestamp,
    );

要在 HTML 中显示 URL,您应该使用 htmlspecialchars($url)& 转换为 &

https://localhost/item?item_id=abcd&redirect=https://www.google.com/&timestamp=1616847657

此外,您可以使用 http_build_query() 生成 有效 URL.

public function generateUrl()
{
    $data = [
        'item_id'   => 'abcd',
        'redirect'  => 'https://www.google.com/',
        'timestamp' => $this->timestamp,
    ];
    return 'https://localhost/item?' . http_build_query($data);
}

输出:

https://localhost/item?item_id=abcd&redirect=https%3A%2F%2Fwww.google.com%2F&timestamp=1616849241