Multiply numbers in a mixed line

My problem is to multiply the numbers in a string containing various characters.

For instance,

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 integer (0-9). All numbers from the string $input are multiplied by $k .

+4
source share
5 answers

I would 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 numbers replace only with the numbers px , em or % .

You can also provide $k lambda functions 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); 
+9
source
 $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); 

It uses anonymous functions available with PHP 5.3. If you want to use it in PHP <5.3 you must create a lambda function using create_function () .

+6
source
 preg_replace('/\d+/e', '$0 * $k', $input); 
+5
source

You can 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); 

In this case, the anonymous function syntax introduced in PHP 5.3 is used. Note that this will change all the numbers in the string, not just the style attributes. You will need to use DOM parsing if you want to avoid this.

You may also find that your styles do not double so easily ...

+1
source

Go through char to char and boolean when you find a character that can be interpreted as int (hint: is_int). If you are in an int, keep an eye on the characters you are passing and attach them to the string. Once you find a character that is not int int concatting to a string. Convert this string to a number and multiply by two. Put it in the right place on the line (which you know because you marked the beginning and end of the integer).

Or just do what John Kugelman, AndreKR and netcoder with regular expressions did.

+1
source

Source: https://habr.com/ru/post/1380481/


All Articles