1

I have the following URL structure:

http://website.com/images/folder1/folder2/123456/x500x1000_2x_ImageName.jpg

I need to remove the crop resolution "x500x1000_2x_" from the image name, like so:

http://website.com/uploads/folder1/folder2/123456/ImageName.jpg

I tried numerous things:

$img = preg_replace('/\[x](\d+)[x](\d+)[_2x_]\.*/', '', $img);
$img = preg_replace('/[x]\d[x]\d[_2x_]\.*/', '', $img);
$img = preg_replace('/\/\[x]+\d+[x]+\d+\D+\d\.*/', '', $img);

I am really not good with preg_replace, can anyone help me please?

1 Answer 1

3

This should work for you:

(Here I just replace x\d+x\d+_\d+x_ of the basename() of the url with preg_replace(). At the end I just concatenate the url again with dirname() together)

<?php

    $img = "http://website.com/images/folder1/folder2/123456/x500x1000_2x_ImageName.jpg";
    echo $img = dirname($img) . "/" . preg_replace("/x\d+x\d+_\d+x_/", "", basename($img));

?>

output:

http://website.com/images/folder1/folder2/123456/ImageName.jpg

regex explanation:

x\d+x\d+_\d+x_
  • x matches the character x literally (case sensitive)
  • \d+ match a digit [0-9]
    • Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
  • x matches the character x literally (case sensitive)
  • \d+ match a digit [0-9]
    • Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
  • _ matches the character _ literally
  • \d+ match a digit [0-9]
    • Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
  • x_ matches the characters x_ literally (case sensitive)
Sign up to request clarification or add additional context in comments.

2 Comments

I was about to write that it's going to cause a problem if the name contains underscore but you have already changed it. :-) +1
thanks for that! works great! (someone else must have edited it actually, wasn't me) :-)

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.