所以我有一堆文件名,例如
$filename = "somefile-Page-1.pdf"
$filename = "somefile-Page-2.pdf"
我想要做的是获取文件名中的页码
so that $pageNumber will resurn Page-1
Iv尝试了以下内容:
$pageNum = substr($filename, 0, strpos($filename, 'Page'));
但最终会返回
somefile-
答案 0 :(得分:2)
试试这个:
$filename = 'somefile-Page-2.pdf';
preg_match('/(Page\-(\d+))\.pdf/i', $filename, $matches);
并且matches数组的格式为:
array(size = 3)
0 =>字符串'Page-2.pdf'(长度= 10)
1 =>字符串'Page-2'(长度= 6)
2 =>字符串'2'(长度= 1)
答案 1 :(得分:0)
在您的示例中,您的子字符串从0开始,结束于" Page"位置。尝试
$pageNum = substr($filename, strpos($filename, 'Page'), -4);
从" Page"获取部分直到结束(没有期间和延期,因此-4)。
答案 2 :(得分:0)
$filename = "somefile-Page-2.pdf";
public function getPageNumber($filename) {
// Explodes on "-"
$explodedFilename = explode('-', $filename);
// Find the key to the Page word
$keyToPage = array_search("Page", $explodedFilename);
// If the key is found and the next array item exists, which contains the number, go and return it
if( $keyToPage && isset($explodedFilename[$keyToPage++]) ) {
return $explodedFilename[$keyToPage] . "-" . $explodedFilename[$keyToPage++];
}
return null;
|