douwen7516 2016-12-28 12:51
浏览 52
已采纳

用regex删除PHP中的某些字符串部分

I am trying to remove certain parts of my string using preg_match. I do not know if this is the best scenario.

I have the following string:

Uploaded Today 13:11, Size 117.09 MiB, ULed by demonoidt

I want to get only the 117.09 part of the string. I am using preg_match like this:

$res = preg_replace("/[^0-9]/", "", $string);

But this will return all the numbers found in the string, so I would have something like:

131111709

Any help would be greatly appreciated. Thank you and happy holidays.

  • 写回答

4条回答 默认 最新

  • 普通网友 2016-12-28 12:53
    关注

    You should be using a matching approach rather than the replacing one.

    Use

    /([\d.]+)\s*MiB/
    

    Or, if the Size word is always before the number, then use

    /Size\s*([\d.]+)/
    

    and grab Group 1 value. See the regex demo (or this demo).

    Pattern details:

    • ([\d.]+) - Group 1 capturing 1 or more digits or .
    • \s* - 0+ whitespaces
    • MiB - a sequence of literal chars.

    NOTE that you may make the number matching part more precise by replacing [\d.]+ with \d*\.?\d+.

    PHP demo:

    $re = '/([\d.]+)\s*MiB/';
    $str = 'Uploaded Today 13:11, Size 117.09 MiB, ULed by demonoidt';
    if (preg_match($re, $str, $match)) {
      echo $match[1]; // => 117.09
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。