[英]Regular Expression String Break
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
? 有没有办法使用正则表达式,我可以得到test1
和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. 这个想法是模式将字符串与-NumXNum
匹配,但捕获先前的内容。 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: 如果您确定所有文件名都以000X000结尾(其中0是任意数字),这应该有效:
/^(.*)-[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/
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. 表达式(.*?)-([^-]+\\.jpg)$
将捕获最后一个之前和之后的所有内容-
在.jpg
文件中。 You can then use preg_match()
to match/capture these groups and explode()
to split the -
into different directories. 然后,您可以使用preg_match()
来匹配/捕获这些组,并使用explode()
将-
拆分为不同的目录。
$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
// )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.