문제

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);
도움이 되었습니까?

해결책 2

How about:

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top