tags:

views:

58

answers:

4

ive got files named

1234_crob.jpg
1234.jpg
2323_örja.bmp
2323.bmp
etc

how can i just retrieve numbers eg. 1234 and 2323?

thanks in advance

+2  A: 

First explode on the period, and then explode on the underscore, and then your number is the first element in the returned list.

<?php
$str1 = "1234.jpg";
$str2 = "1234_crob.jpg";

$pieces = explode("_",current(explode(".",$str1)));
echo $pieces[0]; // prints 1234

$pieces = explode("_",current(explode(".",$str2)));
echo $pieces[0]; // prints 1234
?>

Yes, I realize this is not a regular expression, but this is too simple a task to use regular expressions.

EDIT: Modified code to work for your newly edited formatting examples. EDIT: Modified to fit cleanly in one line of code.

Roman Stolper
Auch... Regex would be simpler! =) Also, some of the filenames may not have numbers at all (at least that was what the asker commented on my answer).
Alix Axel
@Alix Axel: Hehe, perhaps thats true. I just always prefer to use built in functions if at all possible. I guess can use is_numeric() to test if the $pieces[0] is a number. But I see what you're saying, now this code DOES seem like its getting complicated compared to regex.
Roman Stolper
+3  A: 

If the file names all start with numbers there is no need to use regular expressions, try this instead:

foreach (glob('/path/to/dir/{0,1,2,3,4,5,6,7,8,9}*', GLOB_BRACE) as $file)
{
    echo $file . ' = ' . intval(basename($file)) . "<br />\n";
}

This updated glob pattern will only match filenames that start with a digit, as you requested.


@ghostdog74: You're right.

foreach (glob('/path/to/dir/{0,1,2,3,4,5,6,7,8,9}*', GLOB_BRACE) as $file)
{
    echo $file . ' = ' . filter_var(basename($file), FILTER_SANITIZE_NUMBER_INT) . "<br />\n";
}
Alix Axel
note: intval will turn "045" in "045_image.jpg" into 45.
ghostdog74
@ghostdog74: I missed that one, fixed now.
Alix Axel
+2  A: 

Assuming you only pass in filenames (and not filepaths), the following should retrieve all consecutive numbers 0-9:

function getDigits($fn) {
    $arr = array();
    preg_match('/[0-9]+/', $fn, $arr);
    return $arr;
}

EXAMPLE USAGE

var_dump(getDigits('hey_12345.gif'));
/*
output:
array(1) {
  [0]=>
  string(5) "12345"
}
*/

var_dump(getDigits('123487_dude.jpg'));
/*
output:
array(1) {
  [0]=>
  string(6) "123487"
}
*/
cballou
A: 

try this. If you have numbers like 045_test.jpg, using intval will give you 45 instead of 045

$path="/path/[0-9]*";
foreach (glob($path) as $files ){
    $base=basename ($files);
    $s   = preg_split("/[^0-9]/",$base,2);
    echo $s[0]."\n";
}
ghostdog74