PHP Question

Replace dots in URL with dash

i want to raplace dots in url with preg_replace

How can i do it?

The URL is:

http://localhost/../images/

I need it to become:

http://localhost/images/

I try to make it like this:

$url = 'http://localhost/../images/';
$final = preg_replace('\/', '/\..\/', $url);


I try also like this:

$url = 'http://localhost/../images/';
$final = preg_replace('/', '/../', $url);

Answer

Your preg_replace usage is incorrect, but you don't need a regex for this anyway. For static replacements just use str_replace.

$url = 'http://localhost/../images/';
$url = str_replace('..', '', $url);

but your probably also should include the / in the search.

Your preg_replace is inverted the pattern is the first parameter and the replacement value second. http://php.net/manual/en/function.preg-replace.php

So the correct preg_replace would be:

$url = 'http://localhost/../images/';
$final = preg_replace('/\.\./', '/', $url);

Also this is putting a third / between the domain and directory. The /s are delimiters in the pattern, did you mean for that?

Note the .s are special characters and need to be escaped.