ajsie
ajsie

Reputation: 79686

get number from file with regexp?

I've got files named

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

How can I just retrieve numbers e.g. 1234 and 2323?

Upvotes: 1

Views: 141

Answers (4)

Alix Axel
Alix Axel

Reputation: 154543

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

Upvotes: 3

ghostdog74
ghostdog74

Reputation: 342363

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

Upvotes: 0

Corey Ballou
Corey Ballou

Reputation: 43457

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"
}
*/

Upvotes: 2

Roman
Roman

Reputation: 3198

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.

Upvotes: 2

Related Questions