所以,现在我有了一个文件。该文件位于 /home/johndoe/index.html
。
我使用 XAMPP 之类的东西进行托管,它在 localhost
托管文件夹 /home
。
这是我拥有的变量列表:
$server_addr = "localhost";
$server_root = "/home";
$file_dir = "/home/johndoe/index.html";
现在,在 PHP 中,我尝试获取访问 /home/johndoe/index.html
的链接。
我想做的事:
function getLink($file_dir, $server_addr, $server_root) {
// Do something here
return "SOMETHING HERE";
}
echo getLink("/home/johndoe/index.html", "localhost", "/home");
// Expect 'localhost/johndoe/index.html' here.
我认为只在事情上做事并不是明智的做法。
是否有任何 native 函数,或者如何通过“使用”文件来编写函数而不是对这三个字符串执行某些操作?
最佳答案
所以你基本上想获取 $server_addr,从中删除 $server_root 并将 localhost 放在它前面(我认为,是从我可以破译你的问题中收集到的 XD)
我会这样做:
首先,将 $server_root 从“/home”更改为“/home/”
然后:
//Variables to use
$server_addr = "localhost";
$server_root = "/home/";
$file_dir = "/home/johndoe/index.html";
//Function to get a click-able link
function getLink($file_dir, $server_addr, $server_root){
//URL-ise? $server_addr
$server_addr = 'http://' . $server_addr . '/';
/**
* Here we only want to replace the FIRST occurence of $server_root within $file_dir with $server_addr
* */
//Get the position of $server_root, in $file_dir, to make sure that it exists
$root_pos = strpos($file_dir, $server_root);
//Get the length of $server_root
$root_len = strlen($server_root);
//If it is not exactly (!==) equal to false (as 0 will be the case if it is at the very start)
if($root_pos !== false){
//Set the results by replacing only the first occurence
$results = substr_replace($file_dir, $server_addr, $root_pos, $root_len);
//Turn it in to a URL - Remove target="_blank" if you do not want it opening in a new tab
$results = '<a href="' . $results . '" target="_blank">This is a link</a>';
//Return the results
return $results;
}
}
echo getLink($file_dir, $server_addr, $server_root);
这将做什么:
获取“针”的长度和“针”起点的位置。
然后它将用替换内容替换从起始位置开始的所有内容(其长度)。
这是一种仅替换第一次出现的/home/的简单方法,以防实际 URL 中的某处有/home/。我选择此方法而不是 preg_replace 是因为您使用的变量可以包含任何内容,而 preg_replace 对于如此简单的事情来说有点繁重和复杂。
我希望这能起作用。
关于javascript - 如何从 JavaScript 中的服务器链接获取文件的直接链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009915/