1

I'm trying to remove a forward-slash from the end of a string.

Seems simple, but I'm having some issues. A really weird charactar is showing up at the end of the string. See my code:

function removeSlash($currentURL)
{

    if ( strpos($currentURL , '/') == (strlen($currentURL)-1) )
            $currentURL = substr( $currentURL, 0, -1 );

    return $currentURL;

}

$url = 'http://bob.com/';
var_dump( removeSlash($url) );

output:

string(15)"http://bob.com"

The above var_dump says 15 chars were returned, but there is actually 14...

So I ignore it. Then I write a little more code to store it in a DB. The invisible character emerges!

In phpMyAdmin, when i edit the row that the output was inserted in, this is what shows up (in the text field):

http://bob.com

No idea how that's happening. I've tried str_replace(), $var[15] = '' and a load of other methods. All are doing the same!

4
  • 1
    I guess it could be the string terminating null byte. Have you tried getting the ascii code of that character? Use ord() on each character of the string to find out the ascii value. Commented May 30, 2013 at 13:30
  • Just a sec. I'll do that now. Commented May 30, 2013 at 13:38
  • Are you storing it into a binary field rather than a varchar? What kind of DB are you using? Commented May 30, 2013 at 13:41
  • I'm storing it in a varchar field using a MySQL db. Commented May 30, 2013 at 13:49

2 Answers 2

2

Simple case would be to use

rtrim($currentUrl, "/");

But based on comments you may have more luck with this.

function removeSlash($currentURL)
{

    return preg_replace('/[\x00-\x1F\x80-\xFF]/', '', rtrim($currentURL));
}
Sign up to request clarification or add additional context in comments.

9 Comments

I support this answer, though, I don't see any reason to put it in a function by itself. Just use rtrim($url, '/'); everywhere.
Hmm, this issue is still occurring.
Try with the updated answer... this should filter out all of the unprintable characters.
Maybe there is some sort of character encoding issue going on between PHP and the database. I'm out of ideas.
Ah,I tried rtrim($currentURL); (without the second param). Your edit seems to have worked (rtrim($currentURL,"/");). But why? What was that? Why did it occur? And what does rtrim() do to solve it?
|
0

You could try:

$url = trim($url, '/');

Your issue is extremely weird though, this may not be the issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.