替换所有出现的不是以开头的


Replace all occurrences of not starting with

这应该很简单。我想更改所有这些子字符串:

''somedrive'some'path

进入

file://''somedrive'some'path

但是如果子字符串已经有了file://,那么我不想再追加它。

这似乎没有任何作用:

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

我做错了什么?此外,上述内容没有考虑到已经存在的file://的测试;处理这个问题的最佳方法是什么?

更新测试输入:

$test = '
file://''someserver'some'path
''someotherserver'path
';

测试输出:

file://''someserver'some'path
file://''someotherserver'path

谢谢。

您还应该考虑string中的转义序列。

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

使用正则表达式检查给定的子字符串是否以file://开头。如果是,什么都不要做。如果没有,请在字符串的开头附加file://

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

作为一个函数:

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

测试用例:

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

输出:

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

这将为您提供所需的输出。正如php.net所说,双斜杠将被转换为单斜杠。

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

请尝试以下操作:

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