user3865410
user3865410

Reputation: 13

php regex wordpress image names

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]

Upvotes: 1

Views: 985

Answers (3)

Braj
Braj

Reputation: 46841

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"
  }
}

Upvotes: 1

Karl
Karl

Reputation: 833

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

Upvotes: 0

elixenide
elixenide

Reputation: 44831

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.

Upvotes: 2

Related Questions