Reputation: 5834
My trouble is to multiply numbers in string that contains various characters.
For example,
Input:
$k = 2;
$input = '<div style="padding:10px 15px; font-size:1em ;height:2%;"></div>';
Output:
<div style="padding:20px 30px; font-size:2em ;height:4%;"></div>
Edit
$k
can be any whole number (0-9). All numbers from $input
string are multiplied by $k
.
Upvotes: 4
Views: 2112
Reputation: 758
Iterate through the string char by char and have a boolean keeping track of when you find a character that can be interpreted as an int (hint: is_int). If you are in an int keep track of the characters you are traversing and concat them onto a string. As soon as you find a character that is not an int stop concatting onto the string. Convert this string to a number and multiply by two. Put it in the right spot in the string (which you know because you marked the beginning and end of the integer).
Or just do what John Kugelman, AndreKR and netcoder did with the regexes.
Upvotes: 1
Reputation: 67735
I'd use preg_replace_callback
:
$input = '<div style="padding:10px 15px; font-size:1em ;height:2%;"></div>';
$output = preg_replace_callback('/([0-9]+)\s*(px|em|%)/i', function($matches){
$k = 2;
return ($matches[1] * $k).$matches[2];
}, $input);
The above only replace numbers followed by px
, em
or %
.
You could also provide $k
to the lambda function yourself, for more flexibility:
$k = 2;
$output = preg_replace_callback('/([0-9]+)\s*(px|em|%)/i', function($matches) use ($k){
return ($matches[1] * $k).$matches[2];
}, $input);
Upvotes: 11
Reputation: 33697
$k = 2;
$f = function ($i) use ($k) {
return $i[0] * $k;
};
$s = '<div style="padding:10px 15px; font-size:1em ;height:2%;"></div>';
echo preg_replace_callback('/[0-9]+/', $f, $s);
This uses anonymous functions available since PHP 5.3. If you want to use it in PHP < 5.3 you have to create a lambda function using create_function().
Upvotes: 6
Reputation: 237965
You could do this very easily with a little regex:
$k = 2;
$input = '<div style="padding:10px 15px; font-size:1em ;height:2%;"></div>';
$input = preg_replace_callback('/\d+/', function($matches) use ($k) {
return $matches[0] * $k;
}, $input);
This uses the anonymous function syntax introduced in PHP 5.3. Note that this will alter all numbers in the string, not just those in style
attributes. You'll need to use DOM parsing if you want to avoid that.
You may also find that your styles don't double so easily...
Upvotes: 1