2

I'm stuggeling with this regular expression:

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

It changes this: /public_html/ftp/Products/1010_Air+Cooled+Condenser/productsheet_Rotary+Drum+Dryer+BR.pdf

To this: html/Air+Cooled+Condenser/Rotary+Drum+Dryer+BR.pdf

Expected result: /public_html/ftp/Products/Air+Cooled+Condenser/Rotary+Drum+Dryer+BR.pdf

"/productsheet_" could also be "/fish-cb_" or "/appeltaartenbakker_"

"/1010_" is always a number with this length.

2
  • 1
    Does it mean you do not want to match that pattern at the start of the string? Try (?!^)\/[^\/]+_. Or (?!^)\/[^_\/]+_ if you only need to remove the part after a / and before the first _ in that subpart. Commented Jan 10, 2018 at 10:04
  • @WiktorStribiżew could you explain what you just did there? It works! Commented Jan 10, 2018 at 10:29

2 Answers 2

2

I believe you are looking for

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

See the regex demo. If you need to make it stop before the first _, add the underscore to the [...]: '~(?!^)/[^_/]+_~'.

Details

  • (?!^) - not at the start of the string
  • / - a / char (no need to escape as I am using ~ as a regex delimiter char)
  • [^/]+ - 1 or more chars other than /
  • _ - a _ char.

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
Sign up to request clarification or add additional context in comments.

Comments

2

Depending on how well formed those file paths are you could try:

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

Which I tested in php 7.0.3 and in vim with:

/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

Using this command and very magic mode \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

2 Comments

I meant that "/productsheet_" could be any string.
Updated to match any string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.