Using ereg_replace or preg_replace to leave part of a filename in php
I am trying to leave only the prefix (WST in the example below) and the number. Any suffix and file extension should be removed. This should leave me with the product code in tact.
Here are three possible value开发者_StackOverflow社区s:
39159 FLAN.jpg
22201-HAV.jpg
WST 503.jpg
The output I need for these three examples is:
39159
22201
WST 503
Here is my current ereg_replace
, but it also removes the prefix before the number:
$number = ereg_replace("[^0-9]", "", $value);
One option is to remove anything after the last digit. This may not work as expected if you have more than one number in the name:
preg_replace("/\D+$/", "WST 503.jpg", "");
Another, probably stronger option is to capture the first number, and anything before it:
preg_match("/^\D*\d+/", "WST 503.jpg", $matches);
print_r($matches); // [0] => WST 503
The ereg* functions are deprecated. You should not use them anymore.
$name = basename($value, '.jpg');
Now you have the filename without extension in $name
. You can split the name and number into separate variables like this:
$name = str_replace('-', ' ', $name);
if (is_numeric($name[0])) {
list($number, $garbage) = explode(' ', $name);
$prefix = null; unset($garbage);
}
else list($prefix, $number) = explode(' ', $name);
This code only works correctly if the prefix never starts with a number though. But you get the idea.
<?php
function showProductNumberFromFilename($filename) {
// split filename
$filenameParts = explode('.', $filename);
// get extension
$extension = end($filenameParts);
// remove extension
$productNumber = str_replace($extension, '', $filename);
return substr($productNumber, 0, -1);
}
// echos 3159 FLAN
echo showProductNumberFromFilename('39159 FLAN.jpg');
// echos 22201-HAV
echo showProductNumberFromFilename('22201-HAV.jpg');
// echos WST 503
echo showProductNumberFromFilename('WST 503.jpg');
?>
quick and dirty script ;-)
精彩评论