duano3557 2016-03-05 08:02
浏览 53
已采纳

从字符串中使用php正则表达式获取单词

This is my strings

905 Lumens/7.2W/3000K/82CRI/L85 50Khrs
1224 Lumens - 9.6W - 3000K
1632 3000K 12.8W 50Khrs
2448 Lumens/3000K/19.2W 150Khrs

Now I want to get only the word that have number with W Like: 7.2W, 9.6W

I want to get this in a variable using regular expression.

My code is: $watt = preg_match("/[\d]+W/", $string);

currently my code return with array, but I want only string with 7.2W or 9.6W or similar ..

Please help.

  • 写回答

1条回答 默认 最新

  • douchuituo3032 2016-03-05 08:07
    关注

    First of all - founded matches are gathered in a third argument $matches.

    Second - you need to consider a dot(.) in your regexp:

    preg_match("/(\d+\.\d+W)/", $string, $matches);
    print_r($matches);
    echo $matches[0];   // full match found
    

    If . is optional - then:

    preg_match("/(\d+(\.{0,1})\d+W)/", $string, $matches);
    print_r($matches);
    echo $matches[0];   // full match found
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分