0

So i have a bunch of file names such as

  $filename = "somefile-Page-1.pdf" 
  $filename = "somefile-Page-2.pdf"

What im trying to do is get the page number in the file name

so that $pageNumber will resurn Page-1

Iv tried the follwoing:

$pageNum = substr($filename, 0, strpos($filename, 'Page'));

but this ends up returning

 somefile-
1
  • Why are you starting at 0. you should start the substring where the filename starts. substr($filename, strpos($filename, 'Page'), -4); Commented Oct 29, 2014 at 22:55

3 Answers 3

2

Try this:

$filename = 'somefile-Page-2.pdf';
preg_match('/(Page\-(\d+))\.pdf/i', $filename, $matches);

and the matches array will have the format:

array (size=3)

0 => string 'Page-2.pdf' (length=10)

1 => string 'Page-2' (length=6)

2 => string '2' (length=1)

Sign up to request clarification or add additional context in comments.

Comments

0

In your example your substring starts at 0 and ends at "Page" position. Try

$pageNum = substr($filename, strpos($filename, 'Page'), -4);

to get the part from "Page" until the end (without period and extension, thus -4).

Comments

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;
|

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.