Pergunta

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);
Foi útil?

Solução 2

How about:

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

Outras dicas

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top