2011-08-17 69 views
1

我有一個輸出路徑的功能,這裏有一些結果:PHP字符串格式化(SUBSTR)

http://server.com/subdirectory/subdiretory/2021/12/file.txt 
http://server.com/subdirectory/subdiretory/something/else/2016/16/file.txt 
http://server.com/subdirectory/subdiretory/2001/22/file.txt 
C:\totalmess/mess\mess/2012/06/file.txt 

我希望削減一切從這些除外文件名和兩個父目錄,所以上述的那些看起來像:

/2021/12/file.txt 
/2016/16/file.txt 
/2001/22/file.txt 
/20012/06/file.txt 

所以基本上我必須從最後找到第三個「/」,並顯示它之後的一切。

我不知道PHP不太好,但我想這是很容易實現與SUBSTR(),stripos函數()和strlen的(),所以:

$string ="http://server.com/subdirectory/subdiretory/2001/22/file.txt" 
$end = strlen($string); 
$slash = // How to get the right slash using stripos()? 
$output = substr($string, $slash, $end); 
echo $output; 

這是正道這樣做,或者有另一個內置函數可以搜索字符串中的第n個符號?

回答

3

我說放棄str功能,只是explodearray_sliceimplode它=)

$end='/'.implode('/',array_slice(explode('/',$string),-3)); 
+0

+1毆打我對我的答案:) – Cfreak

+0

你,當然需要,如果你這樣做是爲了得到一個字符串返回重新破滅。 (另外,你不需要傳遞'3'長度的參數; array_slice默認會包含到數組的最後。) –

+0

@John,感謝關於不必要的參數的註釋,我實際上已經捕獲了'implode '在你的筆記之前;) – Shad

-1

爆炸,然後爆是真正的輕鬆。但是,如果您想使用字符串函數,則可以使用strrpos

$string ="http://server.com/subdirectory/subdiretory/2001/22/file.txt" 
$slash = strrpos($string, '/', -3); // -3 should be the correct offset. 
$subbed = substr($string, $slash); //length doesn't need to be specified.