dongtangyi8962 2019-05-26 16:26
浏览 198

如何从字符串中提取数字并添加到数组?

I want to convert this string:

<5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>

to an array with key value

I would really appreciate the help

I tried different xmlParse strategies but it is not exactly an xml.

$xml = new \SimpleXMLElement("<5>20825.24</5><7>0.0</ 7><8>0.0</8>");

Response: String could not be parsed as XML

I expect an array like this:

[5=>20825.24,7=>0.0,8=>0.0]
  • 写回答

4条回答 默认 最新

  • dpd7195 2019-05-26 16:32
    关注
    <?php
    
    $subject = '<5> 20825.24 <7> 0.0 <8> 0.0';
    $pattern = '/\<(\d)\>\s+(\d+\.\d+)/u';
    $result = preg_match_all($pattern,$subject,$output);
    
    $numbers = $output[1];
    $output = $output[2];
    $outTotal = [];
    
    foreach ($numbers as $key => $number) {
        $outTotal[$number] = $output[$key];
    }
    var_dump($outTotal);
    

    gives:

    array(3) {
      [5]=>
      string(8) "20825.24"
      [7]=>
      string(3) "0.0"
      [8]=>
      string(3) "0.0"
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制