[英]How to remove a double Forward Slash from the end of a URL if there is one
I need help with removing a double slash from a URL entered by the user. 我需要用户从用户输入的网址中删除双斜杠的帮助。 This is for WordPress front end.
这是针对WordPress前端的。
I have an option for users to input any link. 我可以选择让用户输入任何链接。 Once they input/paste link in the value field, I need to add my affiliate code at the end of that link and show the final output (full link) with my affiliate ID.
他们在值字段中输入/粘贴链接后,我需要在该链接的末尾添加我的会员代码,并显示带有我的会员ID的最终输出(完整链接)。
This is the code I used. 这是我使用的代码。
<form onsubmit="return false" oninput="txtfullurl.value = txturl.value +'/affiliateid'">
URL : <input type="text" name="txturl" /> <br><br>
Full URL : <input type="text" name="txtfullurl" > <br><br>
</form>
The problem is that the URL entered by the user might or might not have "/" (forward slash) at the end. 问题在于,用户输入的URL末尾可能带有“ /”(正斜杠)。
Therefore if the link has a double forward slash before my affiliate ID, I need to remove one. 因此,如果该链接在我的会员ID之前有一个双斜杠,我需要将其删除。
How can I do this? 我怎样才能做到这一点?
You should be doing any sort of sanitising or validation on the server. 您应该在服务器上进行任何形式的清理或验证。 The most flexible solution is to make use of the
wp_parse_url
function, used in conjunction with http_build_query
. 最灵活的解决方案是使用
wp_parse_url
函数,该函数与http_build_query
结合使用。
Example 例
$url = 'https://www.google.com//somethingelse';
$parsed_url = wp_parse_url($url);
$query_string = http_build_query([
'affiliate_id' => 'my_id',
]);
$affiliate_link = $parsed_url['scheme'] . '://' . $parsed_url['host'] . '/?' . $query_string;
You could use the trailingslashit()
function to achieve this. 您可以使用
trailingslashit()
函数来实现。
From the WordPress Codex, this function 从WordPress Codex,此功能
Appends a trailing slash.
附加一个斜杠。 Will remove trailing slash if it exists already before adding a trailing slash.
如果在添加尾斜杠之前已经存在尾斜杠,则将其删除。 This prevents double slashing a string or path.
这样可以防止双斜线字符串或路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.