Search code examples
phpstringtext-extractiontext-parsing

Parse filename with extension to isolate leading characters and numeric suffix without the extension


My current code:

$path2 = $file_list1; 
$dir_handle2 = @opendir($path2) or die("Unable to open $path2"); 
while ($file2 = readdir($dir_handle2)) { 
if ($file2 == "." || $file2 == ".." || $file2 == "index.php" ) 
    continue; 
echo '' . $file2 . '<br />'; 
} 
closedir($dir_handle2);
echo '<br />';

When $file2 is returned, the end of the string will always be a number plus the file extension .txt, like this:

file_name_here1.txt
some_other-file10.txt

So my question is, how can I separate $file2 so it returns the string in two parts, $file_name and $call_number like this?:

echo 'File: ' . $file_name . ' Call: ' . $call_number . '<br />';

Returns:

File: file_name_here Call: 1
File: some_other-file Call: 10

instead of this:

echo '' . $file2 . '<br />';

Returns:

file_name_here1.txt
some_other-file10.txt

Late edit:

Suppose filenames occur as file_name_1__123.txt and this_file_name_2__456.txt where the ending is always 2 [underscores][call#].txt. How do I get the call number then?


Solution

  • I'm a big advocate of Regex but I decided to go slightly different here. Check it out:

    $file = 'file_name_here19.txt';
    $file_parts = pathinfo($file);
    $name = $file_parts['filename'];
    $call = '';
    $char = substr($name, strlen($name) - 1);
    while(ord($char) >= 48 && ord($char) <= 57) {
        $call = $char . $call;
        $name = substr($name, 0, strlen($name) - 1);
        $char = substr($name, strlen($name) - 1);
    }
    echo 'Name: ' . $name . ' Call: ' . $call;