开发者

Pulling a number and prefix from filename using PHP

I am currently using the following function to grab the product code number for a filename such as "62017 THOR.jpg"

$number = (int) $value;

Leaving me with 62017

The trouble is some of these files have prefixe开发者_开发技巧s which need to be left in place ie "WST 62017.jpg"

So im after WST 62017

not

62017

Could someone help me, either redo what im using or alter ?


replace all characters except the numbers from the image name and get only numbers.

  $number  = preg_replace("~[^0-9]~", "", $value);


If you want to capture everything before the number and the number as well, you can use:

$value = "WST 62017.jpg";
$number = preg_replace('/^(.*?\d*)\..*/',"$1",trim($value));
// $number is "WST 62017"

See it


You could do it like this:

$value = preg_replace('/^(.*\d+).*$/', '\1', $filename);

It should replace everything after the first numeric value with nothing, leaving everything in front of it in place. Note that you wont't be able to cast the number to int, then.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜