2010-03-27 108 views
2

我得到这个代码问题从转换路径字符串 “/”, “”

$ =的current_path str_replace函数( '\', '/',GETCWD()); // c:// xampp/htdoc

为什么它无法在目录补丁中用'/'替换'\'?为什么是这个原因以及如何处理这个问题?

编辑此代码用于返回路径(或类似的东西)使用HTML标记基地。代替\作为



$current_path = getcwd(); 

function get_basepath() { 
    global $current_path; 

    $current_path = str_replace('\\', '/', $current_path);      // C:\xampp\htdocs\php\gettingstarted 

    $cur_root = $_SERVER['HTTP_HOST'];    // localhost 
    $cur_docroot = $_SERVER['DOCUMENT_ROOT'];  // C:/xampp/htdocs/ 
    $cur_filepath = $_SERVER['SCRIPT_FILENAME']; // C:/xampp/htdocs/php/gettingstarted/index.php 
    $filepath = str_replace($cur_docroot, '', $current_path); 

    return "http://$cur_root/" . $filepath . "/";  // http://localhost/php/gettingstarted/index1.php 
} 

回答

7

由于\转义下一个字符,您需要使用双重\。 :)

$current_path = str_replace('\\', '/', getcwd()); 
+0

是的,我忘记了。非常感谢你 – justjoe 2010-03-27 13:16:33

1

使用\\

$current_path = str_replace('\\', '/', getcwd()); 

\用来逃避与特殊意义的字符。现在\本身是一个具有特殊含义的字符,因此可以用另一个\(如\\)来获得字面值。

+0

嗨,谢谢你的回答。抱歉,我没有选择你 – justjoe 2010-03-27 13:16:14

1

这就是PHP string syntax问题,你根本不需要这个替换。

+0

谨慎解释为什么我不需要这个替换? – justjoe 2010-03-27 13:18:19

+0

@justjoe关心解释为什么你需要更换,如果一切正常,没有更换? – 2010-03-27 13:28:07

+0

我想在我创建的页面中使用html标签库。从getcwd()的返回值,我得到路径目录,然后我将字符串替换它与我的$ _SERVER ['DOCUMENT_ROOT'] ...在最终的结果将是 类似
HTTP://localhost/php/gettingstarted/ – justjoe 2010-03-27 14:01:34

1
$current_path = str_replace('\\', '/', getcwd()); //c://xampp/htdoc