doubi7306 2018-01-08 21:15
浏览 42
已采纳

PHP字符串操作 - 在特定片段后插入值

I have a string val of H: 35" V: 24 1/2" I can extract the 35 and 24 perform a metric conversion calculation then,
(and this is where i'm stuck),
remake the string to look like H: 35" (89 cm) V: 24 1/2" (62 cm)?

I found regex that could pull the int by

$str = 'H: 35" V: 24 1/2"';
preg_match_all('!\d+!', $str, $matches);
print_r($matches, true);  
//Array ( [0] => 35 [1] => 24 [2] => 1 [3] => 2 ) )

But after this, how can I remake the original string and insert the array values after each of the pieces?

FINAL thank you @AbraCadaver for the answer, however I found the fraction 24 1/2 was not getting calculated so here was my final

$str = preg_replace_callback('!(\d+( \d+/\d+)?")!',
   function($matches) {

        if(isset($matches[2])){
            $fraction = $matches[2];
            if( strpos( $fraction, '/' ) !== false ) {
                $ints = explode('/', $fraction);
                $fraction = $ints[0] / $ints[1];
            }
        }

      $new  = isset($matches[2]) ? $matches[1] + $fraction : $matches[1];
        $new *= 2.54;
        return $matches[1] . " (" . round($new) . " cm)" . "<br>";
   }
   , $str);
  • 写回答

2条回答 默认 最新

  • doutan2228 2018-01-08 21:37
    关注

    I would use preg_replace_callback(). Just add round() if needed.

    Capture digits \d+ followed by an optional space followed by optional digits / digits ( \d+/\d+)? and the inch symbol ":

    $str = preg_replace_callback('!(\d+( \d+/\d+)?")!',
             function($matches) {
                 $new  = isset($matches[2]) ? $matches[1] + $matches[2] : $matches[1];
                 $new *= 2.54;
                 return $matches[1] . " ($new cm)"; //or round($new)
             }
             , $str);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同
  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题