我在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/×tamp=1616847657
这是我的密码。
public function generateUrl()
{
$url = sprintf(
'%s%s?item_id=%s&redirect=%s×tamp=%s',
'https://localhost',
'/item',
'abcd',
'https://www.google.com/',
$this->timestamp,
);
return $url;
}
如果我用其他东西替换timestamp
字符串,结果会很好。timestamp
出了什么问题?如何解决?
谢谢。
sprintf
没有任何问题,×
是乘号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×tamp=1616849241