我有两条路径需要剥离回Views文件夹,然后检查该文件夹中是否存在文件。
查看/ [控制器} / {操作} / {ID}
区/查看/ [控制器} / {操作} / {ID}
我正在寻找一种方法从网址中删除Views /
右边的所有内容答案 0 :(得分:1)
使用http://php.net/substr和http://php.net/function.strpos
的组合$url = substr( $url, 0, strpos($url, "Views/"));
答案 1 :(得分:0)
也许是这样的:
$url = 'Areas/Views/[Controller}/{Action}/{ID}';
$segmentedUrl = explode('/',$url);
$viewsPosition = array_search('Views', $segmentedUrl);
$leftPart = array_slice($segmentedUrl, 0, $viewsPosition+1);
var_dump($leftPart);
答案 2 :(得分:0)
<?php
class Path{
protected $originalPath;
protected $path; // only this path gets manipulated for method chaining reasons
public function setPath($path)
{
$this->originalPath = $path;
$this->path = $path;
}
public function getPartial($partial)
{
if(!isset($this->originalPath))
throw new Exception('No Path set');
// Get the position of partial in our path
$rawPos = strpos($this->path, $partial);
if($rawPos === false)
{
throw new Exception('The Partial: '.$partial. 'was not found within the path');
}
else
{
// If we found the partial let's add the length of the given
// string to figure the actual position
$pos = $rawPos + strlen($partial);
$this->path = substr($this->path, 0, $pos);
return $this;
}
}
public function find($file)
{
$path = $this->path;
$this->rewindPath();
if(is_file($path . '/' . $file))
return true;
return false;
}
protected function rewindPath()
{
$this->path = $this->originalPath;
}
}
// Instantiate Class
$path = new Path();
$path->setPath('Views/[Controller}/{Action}/{ID}');
var_dump($path->getPartial('Views')->find('test.txt'));
$path->setPath('Test/Views/[Controller}/{Action}/{ID}');
var_dump($path->getPartial('Views')->find('test.txt'));
?>
尽管这个问题已经回答了,但我也希望向你展示一个OO方法。路径可以动态设置,您可以使用方法链接在那里搜索文件。这只是一个蓝图,所以你得到了基本的想法。
快乐的编码!