Question

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);
Was it helpful?

Solution 2

How about:

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

OTHER TIPS

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

This is working for me.

what about the below ?

$pattern = '/\//';
$path = '/aaaaa/bbbbb/ccccc/dddd';
preg_replace(array($pattern), array('..'), $path
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top