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:


I need it to become:


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 Source

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.

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.