Reputation: 4693
I am trying to recalculate INT
values of a CSS
string.
PHP string:
$str = "background-repeat:no-repeat; position:absolute; left:522px; top:422px; width:155px; height:178px;";
Then i examine each value
$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] =>
)
From here I would like to run a process and change INT
values that have PX
. So this would affect items [2], [3], [4], [5]
my attempt
foreach ($strArr as $piece) {
$item = preg_match("/\d/", $piece); // check if contains `INT`
if($ss==1){
// run a process here to change int values
}
}
// reconstruct string
// ex: $newStr = "background-repeat:no-repeat; position:absolute; left:261px; top:211px; width:78px; height:89px;";
Any help would be appreciated, thank you.
Upvotes: 0
Views: 95
Reputation: 6081
try:
$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
Upvotes: 1
Reputation: 1582
You will match more precisely using the regex /(?<=:)\d+(?=px)/g
, This will get you only the numeric part, You can then do the calculation.
Updated, try this.
<?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';
}
}
Upvotes: 2
Reputation: 5371
$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..
Upvotes: 1