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条)

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效