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