Nate
Nate

Reputation: 577

php regex to replace 'any' slashes in a path with directory separator

I am trying to take paths like this:

some/path/here some\other\path

and replace each slash in the paths with PHP's DIRECTORY_SEPARATOR built in constant

I have this:

$subject = '/asdf';
$var = preg_replace('#\\\\#', DS, $subject);
print $var;

but this doesn't replace, it only add.

Thanks for any help.

Upvotes: 3

Views: 4312

Answers (4)

Schleis
Schleis

Reputation: 43800

Rather than using preg_replace, why not just use str_replace?

$var = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $subject);

https://www.php.net/manual/en/function.str-replace.php

Upvotes: 12

Willem Mulder
Willem Mulder

Reputation: 14014

It should replace, not add. But try this:

preg_replace('/[\\]/', DS, $subject);

Should also work.

Upvotes: 0

Smuuf
Smuuf

Reputation: 6544

If you don't explicitly need regex, then this is the way:

$string = "some/path/here some\other\path";
$ds = DIRECTORY_SEPARATOR;
$result = str_replace(array("/","\\"),$ds,$string);
echo $result;

Outputs: some/path/here some/other/path

Upvotes: 0

Sidux
Sidux

Reputation: 557

Because you have 2 slashes try with #\\#

Upvotes: 0

Related Questions