简体   繁体   中英

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.

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.

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.

Therefore if the link has a double forward slash before my affiliate ID, I need to remove one.

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 .

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.

From the WordPress Codex, this function

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM