PHP:preg_replace文件路径

时间:2018-01-10 10:02:29

标签: php regex preg-replace

我正在使用这个正则表达式:

preg_replace('/\/[\s\S]+?_/', '/', $currentFile)

它改变了这个: /public_html/ftp/Products/1010_Air+Cooled+Condenser/productsheet_Rotary+Drum+Dryer+BR.pdf

对此:html/Air+Cooled+Condenser/Rotary+Drum+Dryer+BR.pdf

预期结果: /public_html/ftp/Products/Air+Cooled+Condenser/Rotary+Drum+Dryer+BR.pdf

"/productsheet_"也可以是"/fish-cb_""/appeltaartenbakker_"

"/1010_"始终是具有此长度的数字。

2 个答案:

答案 0 :(得分:2)

取决于您可以尝试这些文件路径的形式:

preg_replace('/[0-9]{4}_(.+\/).+_/','\1',$currentFile)

我在php 7.0.3和vim中测试过:

/public_html/ftp/Products/1010_Air+Cooled+Condenser/productsheet_Rotary+Drum+Dryer+BR.pdf
/public_html/ftp/Products/1020_Air+Cooled+Condenser/fish-cb_Rotary+Drum+Dryer+BR.pdf
/public_html/ftp/Products/1030_Air+Cooled+Condenser/appeltaartenbakker_Rotary+Drum+Dryer+BR.pdf

使用此命令和非常神奇的模式\v

:%s/\v[0-9]{4}_(.+\/).+_/\1/g
/public_html/ftp/Products/Air+Cooled+Condenser/Rotary+Drum+Dryer+BR.pdf
/public_html/ftp/Products/Air+Cooled+Condenser/Rotary+Drum+Dryer+BR.pdf
/public_html/ftp/Products/Air+Cooled+Condenser/Rotary+Drum+Dryer+BR.pdf

答案 1 :(得分:2)

我相信你在寻找

'~(?!^)/[^/]+_~'

请参阅regex demo。如果您需要在第一个_之前停止,请将下划线添加到[...]'~(?!^)/[^_/]+_~'

<强>详情

  • (?!^) - 不在字符串的开头
  • / - 一个/字符(无需转义,因为我使用~作为正则表达式分隔符char)
  • [^/]+ - 除/
  • 以外的1个或多个字符
  • _ - _字符。

PHP demo:

$str = '/public_html/ftp/Products/1010_Air+Cooled+Condenser/productsheet_Rotary+Drum+Dryer+BR.pdf';
$result = preg_replace('~(?!^)/[^/]+_~', '/', $str);
echo $result; // => /public_html/ftp/Products/Air+Cooled+Condenser/Rotary+Drum+Dryer+BR.pdf