Replace inverted bars with single bars - image URL

Asked

Viewed 4,875 times

3

I am trying to remove the backslashes to open the image URL, I found a way to replace, but part of my string was lost:

function formatURL( $url )
{    
    echo $url."<br />";

    $url = str_replace('\\', '/', $url);

    echo $url."<br />";
}

echo "http://10.0.0.1/fotoou/aplic\1\7\1\3\9\8\1\\1893171_1.jpg<br />";

$url = formatURL("http://10.0.0.1/fotoou/aplic\1\7\1\3\9\8\1\\1893171_1.jpg");

echo $url;

The strange thing is that my return is:

http://10.0.0.1/fotoou/aplic\9\8\1893171_1.jpg
http://10.0.0.1/fotoou/aplic\9\8\1893171_1.jpg
http://10.0.0.1/fotoou/aplic/9/8/1893171_1.jpg

Part of the lost string:

\1\7\1\3\

1 answer

3


This is because, the way you declared the string, you should have put two backslashes for each bar you want to print. It’s called "escaping the bars".

See about this in "Escape Sequences" in the [PHP Handbook].(http://php.net/manual/en/language.types.string.php)

In the case of double quotes declared strings (as in your example), using this backslash alone causes the PHP recognize that you are wanting to insert a special character.

In case, you have two options:

  1. You can simply replace the aspas duplas for aspas simples
  2. Or you put two bars instead of two bars (if you’re going to use the Apas doubles ")

Possible changes to your code

Example 1 (String with double quotes):

$url = formatURL("http://10.0.0.1/fotoou/aplic\\1\\7\\1\\3\\9\\8\\1\\1893171_1.jpg");

Example 2 (String with single quotes):

$url = formatURL('http://10.0.0.1/fotoou/aplic\1\7\1\3\9\8\1\\1893171_1.jpg');
  • Opa valeu Wallace! And in case my string is coming from a variable? How can I guarantee the integrity of the string?

  • The operation is the same @Alessandrogomes. $teste = "http://teste\\path\\to\\action"

  • in my case is the following : $url = $registro["FOTO1"]; and the string already comes with only one bar

  • No, it doesn’t come with "one bar". That "one bar" I said is in statement of the string (where you really need to escape, on account of the PHP interpreter). If it comes from elsewhere (as in $_POST or the database), just pass the parameter in its function, because the PHP will process it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.