1

I would like to use the PHP function preg_replace to remove the appended dimensions in image filenames. Our CMS adds dimensions to the end of the filename, right before the extension. For legacy reasons, the naming conventions are inconsistent: sometimes an underscore preceeds, other times, a dash.

It would be super useful to strip the dimensions out in my frontend code.

Is there a single PHP regular expression that would match in these scenarios:

Example-Filename,-lorem-ipsum_999x999.jpg  

[need to match: _999x999]

Example-Filename2-lorem,-ipsum-42x42.PNG

[need to match: -42x42]

Example-Filename3-lorem-Ipsum-dolor-blah_0128x0256.jpeg

[need to match: _0128x0256]

3 Answers 3

2

This will do what you want:

/[_-]\d+x\d+(?=\.[a-z]{3,4}$)/i

Demo

Explanation:

  • [_-] matches _ or -
  • \d+ matches a string of digits
  • x is literal x
  • \d+ matches a string of digits
  • (?=\.[a-z]{3,4}$) is a lookahead group, saying the match must be followed by ., 3-4 letters, and the end of the string.
Sign up to request clarification or add additional context in comments.

1 Comment

This one works very well in Wordpress theme because of a scenario I had not imagined when I originally posted the question. When the input has no dimensions (tends to happen in a Wordpress theme, eg: Example-Filename.jpg), this solution simply returns the original filename unmodified.
1

Try with Positive Lookahead and Capturing group

[_-][^_-]+(?=\.)

Live demo

Your PHP code would be,

<?php
$data = <<<'EOT'
Example-Filename,-lorem-ipsum_999x999.jpg
Example-Filename2-lorem,-ipsum-42x42.PNG
Example-Filename3-lorem-Ipsum-dolor-blah_0128x0256.jpeg
EOT;
$regex =  '~[_-][^_-]+(?=\.)~';
preg_match_all($regex, $data, $matches);
var_dump($matches);
?>

Output:

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(8) "_999x999"
    [1]=>
    string(6) "-42x42"
    [2]=>
    string(10) "_0128x0256"
  }
}

Comments

0

This regex would match that part /([-_]\d+?x\d+?)\.[a-zA-Z]{3,4}$/

1 Comment

Note that this also matches the file extension, so rather than matching _999x999, it matches _999x999.jpg.

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.