我有一个具有特定结构的文件集合:
COMPANY_DE-Actual-Contents-of-File-RGB-ENG.pdf
细目:
。
在最好的情况下,我的结果将是一个数组,上面的信息带有命名的键,但不知道从哪里开始。
我们将非常感谢您的帮助!
谢谢你,克纳尔
很抱歉这么不清楚,但是有几个变量是不总是存在于文件名中:- DE ->固定选项:'_DE','_BE',或缺席- RGB ->颜色模式,固定选项:'RGB','CMYK','PMS',或缺席- ENG ->语言的文件,固定选项:'GER','ENG',或缺席。
发布于 2012-04-19 08:17:47
试一试
$string = "COMPANY_DE-Actual-Contents-of-File-RGB-ENG.pdf";
$array = preg_split('/[-_\.]/', $string);
$len = count($array);
$struct = array($array[0], $array[1], '', $array[$len-3], $array[$len-2], $array[$len-1]);
unset($array[0], $array[1], $array[$len-3], $array[$len-2], $array[$len-1]);
$struct[2] = implode('-', $array);
var_dump($struct);-
array
0 => string 'COMPANY' (length=7)
1 => string 'DE' (length=2)
2 => string 'Actual-Contents-of-File' (length=23)
3 => string 'RGB' (length=3)
4 => string 'ENG' (length=3)
5 => string 'pdf' (length=3)发布于 2012-04-19 08:41:54
如果可能的话,尽量不要使用正则表达式,或者尽可能简单地使用正则表达式。
$text = "COMPANY_DE-Actual-Contents-of-File-RGB-ENG.pdf";
$options_location = array('DE','BE');
$options_color = array('RGB','CMYK','PMS');
$options_language = array('ENG','GER');
//Does it have multiple such lines? In that case this:
$lines = explode("\n",$text);
//Then loop over this with a foreach, doing the following for each line:
$parts = preg_split('/[-_\.]/', $line);
$data = array(); //result array
$data['company'] = array_shift($parts); //The first element is always the company
$data['filetype'] = array_pop($parts); //The last bit is always the file type
foreach($parts as $part) { //we'll have to test each of the remaining ones for what it is
if(in_array($part,$options_location))
$data['location'] = $part;
elseif(in_array($part,$options_color))
$data['color'] = $part;
elseif(in_array($part,$options_language))
$data['lang'] = $part;
else
$data['content'] = isset($data['content']) ? $data['content'].' '.$part : $part; //Wasn't any of the others so attach it to the content
}这也更容易理解,而不是必须弄清楚regex到底在做什么。
请注意,这假设内容的任何部分都不能是为位置、颜色或语言保留的单词之一。如果这些情况可能发生在内容中,则必须添加诸如isset($data['location'])这样的条件,以检查是否已经找到另一个位置,如果有,则将正确的位置添加到内容中,而不是将其作为位置存储。
发布于 2012-04-19 08:14:02
就像这样:
preg_match('#^([^_]+)(_[^-]+)?-([\w-]+)-(\w+)-(\w+)(\.\w+)$#i', 'COMPANY_DE-Actual-Contents-of-File-RGB-ENG.pdf', $m);
preg_match('#^([^_]+)(_[^-]+)?-([\w-]+)-(\w+)[_-]([^_]+)(\.\w+)$#i', 'COMPANY_DE-Actual-Contents-of-File-RGB-ENG.pdf', $m); // for both '_' and '-'
preg_match('#^(\p{Lu}+)(-\p{Lu}+)?-([\w]+)(\-(\p{Lu}+))?(\-(\p{Lu}+))?(\.\w+)$#', 'COMPANY-NL-Actual_Contents_of_File-RGB-ENG.pdf', $m); // if filename parts divider is strictly '-'
var_dump($m);在最后一个变体中,当我们询问是否没有国家代码(-NL)时,它将为空。但用颜色和语言代码就不是了。你自己试一试,你就会明白它是如何工作的!
https://stackoverflow.com/questions/10223999
复制相似问题