使用 explode 并不是一个坏主意,如果你对 URI 的所有部分感兴趣,你应该看一下
explode 文档。
它的用法如下:
$exploded = explode('/','/path/to/page.html');
echo $exploded[0]; // Will print out '' (empty string)
echo $exploded[1]; // Will print out 'path'
echo $exploded[2]; // Will print out 'to'
echo $exploded[3]; // Will print out 'page.html'
然而据我所知,您想要用第一个字符后面的任何内容(始终为“/”)替换链接,您可以使用substr,如下所示:
// Get whatever is after the first character and put it into $path
$path = substr($_SERVER['REQUEST_URI'], 1);
在您的情况下,这不是必需的,因为您能够预测字符串开头有一个反斜杠。
我还建议使用
关联数组来替换URL。
我会像这样实现整个过程(根据您的要求删除第一个反斜杠):
// Define the URLs for replacement
$urls = array(
'subfolder0' => '/subfolder0/anotherfolder/page.html',
'subfolder1' => '/subfolder1/page.html'
);
// Get the request URI, trimming its first character (always '/')
$path = substr($_SERVER['REQUEST_URI'], 1);
// Set the link according to $urls associative array, or set
// the default URL if not found
$link = $urls[$path] or '/subfolder2/page.html';
或者使用explode函数,只获取URI的第一部分:
// Get the parts of the request
$requestParts = explode('/', $_SERVER['REQUEST_URI']);
// Set the link according to $urls associative array, or set
// the default URL if not found
$link = $urls[$requestParts[1]] or '/subfolder2/page.html';