I am fairly new to regex. I have been trying to break string to get the initial part of the string to create folders.
Here are few examples of the variables that I need to break.
test1-792X612.jpg
test-with-multiple-hyphens-612X792.jpg
Is there a way using regular expression that I can get test1
and test-with-multiple-hyphens
?
You can use a regex like this:
(.*?)-\d+x\d+
The idea is that the pattern will match the string with the -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 the insensitive flag, you could change the regex to:
(.*?)-\d+[Xx]\d+
If you're certain that all filenames end with 000X000 (where the 0's are any number), this should work:
/^(.*)-[0-9]{3}X[0-9]{3}\.jpg$/
The value from (.*)
will contain the part that you're looking for.
In case there could be more or fewer numbers, but at least one:
/^(.*)-[0-9]+X[0-9]+$\.jpg/
You can use this simple regex:
(.+)(?=-.+$)
Explanations :
(.+) : Capture desired part
(?=-.+$) : (Positive Lookahead) Which is following a dashed part
If I understood your question correctly, you want to break the hyphenated parts of a file into directories. The expression (.*?)-([^-]+\\.jpg)$
will capture everything before and after the last -
in a .jpg
file. You can then use preg_match()
to match/capture these groups and explode()
to split the -
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
// )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.