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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line