Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for all strings not containing a specific string

Tags:

regex

php

I need to choose the original image in my example is a 'image1.jpg' with any extension.

image1-150x150.jpg
image1-225x300.jpg
image1-768x1024.jpg
image1.jpg

I've tried the following:

preg_grep("/-([0-9]+x[0-9])+/", $image);

How do I exclude other files and select "image1.jpg"?

like image 964
Andrei Demidow Avatar asked Apr 08 '26 06:04

Andrei Demidow


1 Answers

I wanted to write without PREG_GREP_INVERT, because it will be used in some cases without preg_grep

Then you could use a negative lookahead to negate strings that contain the pattern \d+x\d+:

/^((?:.(?!\d+x\d+))*\.[^.]+)$/gm

It would capture image1.jpg based on the input you provided - example here.

  • ^ - Anchor to match the beginning of the line (since the m flag is used).

  • .(?!\d+x\d+))* - Match zero or more characters not followed by \d+x\d+

  • \.[^.]+ - Match the . character literally followed by one or more characters that are not .

  • $ - Anchor to match the end of the line.

like image 126
Josh Crozier Avatar answered Apr 10 '26 19:04

Josh Crozier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!