分割文件名,只取一部分使用

发布于 2024-10-05 04:23:22 字数 91 浏览 0 评论 0原文

我有一个 $value,例如 22214-HAV.jpg 或 22214 HAV.jpg(注意没有破折号)

我想运行一个快速函数来仅从文件名中提取数字。

I have a $value such as 22214-HAV.jpg or 22214 HAV.jpg (notice no dash)

I want to run a quick function to pull only the number from filename.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

当梦初醒 2024-10-12 04:23:22

一个快速的解决方案,利用 PHP 类型杂技

$number = (int) $filename;

A quick solution, which make use of PHPs type juggling

$number = (int) $filename;
感性 2024-10-12 04:23:22
preg_match('/^\d+/' ,'22214-HAV.jpg', $matches);
var_dump($matches[0]);

观察:

  1. 这只会匹配从头开始的数字。通过删除 ^ 可以允许任何位置。
  2. 这将匹配任何数字序列而不是实际数字。可以通过使用 ([1-9]\d*|0) 代替 \d+ 来限制数字。
  3. 如果未找到匹配项,$matches[0] 将为 null 而不是空字符串。

进一步阅读:

  1. http://www.php.net/manual/en/ function.preg-match.php
  2. http://www.regular-expressions.info/参考.html
preg_match('/^\d+/' ,'22214-HAV.jpg', $matches);
var_dump($matches[0]);

Observations:

  1. This will only match numbers starting exactly from the beginning. Any position can be allowed by removing ^.
  2. This will match any sequence of digits and not actual numbers. Numbers can be restricted by using ([1-9]\d*|0) in place of \d+.
  3. If no match is found $matches[0] will be null and not an empty string.

Further reading:

  1. http://www.php.net/manual/en/function.preg-match.php
  2. http://www.regular-expressions.info/reference.html
情魔剑神 2024-10-12 04:23:22

您可以为此使用爆炸

   //for '-'
            list($reqval)=explode('-', $value); 
    //for space
            list($reqval)=explode(' ', $value); 


        echo $reqval

You can use explode for this

   //for '-'
            list($reqval)=explode('-', $value); 
    //for space
            list($reqval)=explode(' ', $value); 


        echo $reqval
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文