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
?
source to share
You can use regex like this:
(.*?)-\d+x\d+
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+
source to share
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
// )
source to share