php重新计算css字符串的数值

时间:2015-02-07 00:17:50

标签: php regex

我正在尝试重新计算INT字符串的CSS值 PHP字符串:

$str = "background-repeat:no-repeat; position:absolute; left:522px; top:422px; width:155px; height:178px;";

然后我检查每个值

$strArr= explode(";", $str);
// output:
Array
(
        [0] => background-repeat:no-repeat
        [1] =>  position:absolute
        [2] =>  left:522px
        [3] =>  top:422px
        [4] =>  width:155px
        [5] =>  height:178px
        [6] =>
)

从这里开始,我想运行一个流程并更改INT的{​​{1}}值。因此,这会影响商品PX

我的尝试

[2], [3], [4], [5]

任何帮助将不胜感激,谢谢。

3 个答案:

答案 0 :(得分:2)

您将使用正则表达式/(?<=:)\d+(?=px)/g更精确地匹配,这将只获得数字部分,然后您可以进行计算。

更新,试试这个。

<?php
$str = "background-repeat:no-repeat; position:absolute; test:0px; left:522px; top:422px; width:155px; height:178px;";
$strArr= explode(";", $str);
foreach ($strArr as $pieces => $piece) {
    $item = preg_match("/(?<=:)\d+(?=px)/", $piece, $match, PREG_OFFSET_CAPTURE);
    if ($match) {
        $intval = (int)$match[0][0];
        $offset = $match[0][1];
        $newVal = $intval + 100; // your calculation here
        $strArr[$pieces] = substr($piece, 0, $offset) . $newVal . 'px';
    }
}

答案 1 :(得分:1)

尝试:

$str = "background-repeat:no-repeat; position:absolute; left:522px; top:422px; width:155px; height:178px;";
$strArr= explode(";", $str);
foreach ($strArr as $piece) {

  $item = preg_match('/[0-9]+px/', $piece); // check if contains int followed by px
  if($item==1){
      $piece = preg_replace('/[0-9]+px/', '400px',$piece);
  }//here I'm replacing all the INT values to 400px
$myValue[]=$piece;
}
$formattedStr = implode($myValue,';');
echo $formattedStr; //the result string with all the px values changed to 400

答案 2 :(得分:1)

$str = "background-repeat:no-repeat; position:absolute; left:522px; top:422px; width:155px; height:178px;";

// this regex pattern will take any number that ends with px, i.e. 500px, 1px, 20px
preg_match_all('/([0-9+])+px/', $str, $matches);

foreach($matches[0] as $match) {
  $intvalue = (int) $match;
  $str = str_replace($match, '500px', $str); // subsitute 500px for what it should be replaced with
}

// $str is now updated..