我试图在文本中找到(并用其他东西替换)
- 以"/"开头
- 以"/"结尾
- 在这两个/之间可以有任何东西,除了字符串"answers".."
(为了您的信息,我正在搜索和替换目录和文件名,因此应该排除'.'和'..'。)
这是我想出的正则表达式:
/(?!'.|'.'.)([^/]+)/
第二部分
([^/]+)
匹配每个字符序列,排除"/"。不需要字符限制,我只是在解释输入。
第一部分
(?!'.|'.'.)
使用负前瞻断言来排除字符串"answers".."。
然而,这在使用mb_ereg_replace()的PHP中似乎不起作用。
有人能帮我吗?我看不出我的正则表达式出了什么问题。
谢谢。
POSIX正则表达式可能不支持负外观。(我可能错了)
无论如何,由于PCRE-regex通常比POSIX快,我认为您可以使用相同函数的PCRE版本,因为PCRE也使用u
标志支持utf8。
将此代码视为替代代码:
preg_replace('~/(?!'.|'.'.)([^/]+)/~u', "", $str);
编辑:更好的方法是使用:
preg_replace('~/(?!'.)([^/]+)/~u', "", $str);
这有点冗长,但它确实有效:
#/(('.[^./][^/]*)|('.'.[^/]+)|([^.][^/]*))/#
^ |------------| |---------| |---------|
| | | |
| | text starting with |
| | two dots, that isn't |
| | "." or ".." |
| text starting with |
| a dot, that isn't text not starting
| "." or ".." with a dot
|
delimiter
不匹配:
hi
//
/./
/../
匹配:
/hi/
/.hi/
/..hi/
/...
/
戴着它四处玩耍http://regexpal.com/.
我不确定你是否想允许//
。如果你这样做了,把*
放在最后一个/
之前。
我不反对regex,但我会这样做:
function simplify_path($path, $directory_separator = "/", $equivalent = true){
$path = trim($path);
// if it's absolute, it stays absolute:
$prepend = (substr($path,0,1) == $directory_separator)?$directory_separator:"";
$path_array = explode($directory_separator, $path);
if($prepend) array_shift($path_array);
$output = array();
foreach($path_array as $val){
if($val != '..' || ((empty($output) || $last == '..') && $equivalent)) {
if($val != '' && $val != '.'){
array_push($output, $val);
$last = $val;
}
} elseif(!empty($output)) {
array_pop($output);
}
}
return $prepend.implode($directory_separator,$output);
}
测试:
echo(simplify_path("../../../one/no/no/../../two/no/../three"));
// => ../../../one/two/three
echo(simplify_path("/../../one/no/no/../../two/no/../three"));
// => /../../one/two/three
echo(simplify_path("/one/no/no/../../two/no/../three"));
// => /one/two/three
echo(simplify_path(".././../../one/././no/./no/../../two/no/../three"));
// => ../../../one/two/three
echo(simplify_path(".././..///../one/.///./no/./no/../../two/no/../three/"));
// => ../../../one/two/three
我认为返回一个等价的字符串会更好,所以我尊重..
在字符串开头的位置。
如果你不想要它们,你可以用第三个参数$equivale=false来调用它:
echo(simplify_path("../../../one/no/no/../../two/no/../three", "/", false));
// => one/two/three
echo(simplify_path("/../../one/no/no/../../two/no/../three", "/", false));
// => /one/two/three
echo(simplify_path("/one/no/no/../../two/no/../three", "/", false));
// => /one/two/three
echo(simplify_path(".././../../one/././no/./no/../../two/no/../three", "/", false));
// => one/two/three
echo(simplify_path(".././..///../one/.///./no/./no/../../two/no/../three/", "/", false));
// => one/two/three
/(?!('.|'.'.)/)([^/]+)/
这将允许...
作为有效名称。