简体   繁体   English

替换所有不以\\\\开头的\\\\

[英]Replace all occurrences of \\ not starting with

This should be simple. 这应该很简单。 I want to change all of these substrings: 我想更改所有这些子字符串:

\\somedrive\some\path

into

file://\\somedrive\some\path

but if substrings already have a file:// then I don't want to append it again. 但是如果子字符串已经有一个file://那么我就不想再追加它了。

This doesn't seem to do anything: 这似乎无能为力:

var_export( str_replace( '\\\\', 'file://\\\\', '\\somedrive\some\path file://\\somedrive\some\path' ) ); 

What am I doing wrong? 我究竟做错了什么? Also, the above doesn't take into test for file:// already being there; 同样,上面的内容并没有考虑到file://已经存在; what's the best way of dealing with this? 处理此问题的最佳方法是什么?

UPDATE test input: UPDATE测试输入:

$test = '
file://\\someserver\some\path

\\someotherserver\path
';

test output: 测试输出:

file://\\someserver\some\path

file://\\someotherserver\path

Thanks. 谢谢。

You should consider escape sequence in string also. 您还应该考虑string转义序列。

if((strpos($YOUR_STR, '\\\\') !== false) && (strpos($YOUR_STR, 'file://\\\\') === false))
    var_export( str_replace( '\\\\', 'file://\\\\', $YOUR_STR ) ); 

Use a regular expression to check if the given substring starts with file:// . 使用正则表达式检查给定的子字符串是否以file://开头。 If it does, don't do anything. 如果可以,则什么也不做。 If it doesn't, append file:// at the beginning of the string: 如果没有,请在字符串的开头附加file://

if (!preg_match("~^file://~i", $str)) {
    $str = 'file://' . $str;
}

As a function: 作为功​​能:

function convertPath($path) {
    if (!preg_match("~^file://~i", $path)) {
        return 'file://'.$path;
    }
    return $path;
}

Test cases: 测试用例:

echo convertPath('\\somedrive\some\path');
echo convertPath('file://\\somedrive\some\path');

Output: 输出:

file://\somedrive\some\path
file://\somedrive\some\path

编辑多次出现: preg_replace('#((?!file://))\\\\\\\\#', '$1file://\\\\\\\\', $path)

This will work to give you the output you are expecting. 这将为您提供期望的输出。 As php.net says double slash will be converted into single slash. 正如php.net所说,双斜杠将转换为单斜杠。

if (!preg_match('/^file:\/\//', $str)) {
    $str =  "file://\\".stripslashes(addslashes($str));
}

Please try this: 请尝试以下方法:

$string = "\\somedrive\some\path";
$string = "\\".$string;
echo str_replace( '\\\\', 'file://\\\\',$string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM