dmills
dmills

Reputation: 3

Regex to convert directory paths in PHP

Goal - convert a path: /aaaaa/bbbbb/ccccc/dddd to a relative path (to the root): ../../../../

So far I've come up with this regex: /\/.+?\// but this only produces: ..bbbbb..dddd because it is only matching every other pair of slashes, and also matching the slashes. I'm looking for something like a string split, but also replace.

All of my php code:

$pattern = '/\/.+?\//';
$path = '/aaaaa/bbbbb/ccccc/dddd';
echo preg_replace($pattern, '..', $path);

Upvotes: 0

Views: 69

Answers (3)

john pigeret
john pigeret

Reputation: 11

what about the below ?

$pattern = '/\//';
$path = '/aaaaa/bbbbb/ccccc/dddd';
preg_replace(array($pattern), array('..'), $path

Upvotes: 0

user3567510
user3567510

Reputation:

preg_replace('/\/{0,1}(\w+)\/{0,1}/', '../', $path);

This is working for me.

Upvotes: 1

Toto
Toto

Reputation: 91415

How about:

preg_replace(':/[^/]+:', '../', $path);

Upvotes: 0

Related Questions