Regular expression String Break

I am new to regex. I am trying to split a string to get the initial part of the string to create folders.

Here are some examples of variables that I need to break.

test1-792X612.jpg

test-with-multiple-hyphens-612X792.jpg

Is there a way to use a regular expression that I can get test1

and test-with-multiple-hyphens

?

+3


source to share


4 answers


You can use regex like this:

(.*?)-\d+x\d+

      

Working demo

enter image description here



The idea is that the template will match line c -NumXNum

, but capture the previous content. Note the case insensitive flag.

MATCH 1
1.  [0-5]   `test1`
MATCH 2
1.  [18-44] `test-with-multiple-hyphens`

      

If you don't want to use an insensitive flag, you can change the regex to:

(.*?)-\d+[Xx]\d+

      

+3


source


If you are sure all filenames end with 000X000 (where 0 is any number), this should work:

/^(.*)-[0-9]{3}X[0-9]{3}\.jpg$/

      

The from value (.*)

will contain the part you are looking for.



If the number can be more or less, but at least one:

/^(.*)-[0-9]+X[0-9]+$\.jpg/

      

+1


source


You can use this simple regex:

(.+)(?=-.+$)

      

Clarifications

(. +) : Capture the desired part

(? = -. + $) : (Positive Lookahead) that follows the dotted part

Live demo

0


source


If I understand your question correctly, you want to split the portable parts of the file into directories. The expression (.*?)-([^-]+\.jpg)$

will write everything before and after the last one -

in the file .jpg

. Then you can use preg_match()

to match / capture these groups and explode()

to split -

into different directories.

$files = array(
    'test1-792X612.jpg',
    'test-with-multiple-hyphens-612X792.jpg',
);

foreach($files as $file) {
    if(preg_match('/(.*?)-([^-]+\.jpg)$/', $file, $matches)) {
        $directories = explode('-', $matches[1]);
        $file = $matches[2];
    }
}

// 792X612.jpg
// Array
// (
//     [0] => test1
// )
//
// 612X792.jpg
// Array
// (
//     [0] => test
//     [1] => with
//     [2] => multiple
//     [3] => hyphens
// )

      

-1


source







All Articles