I have input strings like
Wires: 8 Pairs: 4
The both numbers may be different for different strings
So, only dividing and only numbers can be different
I need to get the output result like
Wires: 2 Pairs: 4
That is the number of wires should become the result of diving the first number by the second one
Here is my working PHP code:
<?php
$input = 'Wires: 8 Pairs: 4';
$pattern = '(Wires:)(\s)(\d+)(\s)(Pairs:)(\s)(\d+)';
$output = preg_replace_callback('/'.$pattern.'/',
function($m) {
return 'Wires: '.$m[3]/$m[7].' Pairs: '.$m[7];
},
$input);
echo $output;
But the point is, both patterns and replacements should be stored in and loaded from external JSON file as strings.
The patterns are working if I store them in the file, adding two escaping backslashes instead of one like (\\s)(\\d+)
But how to deal with the replacements?
If I try something like
<?php
$input = 'Wires: 8 Pairs: 4';
$pattern = '(Wires:)(\s)(\d+)(\s)(Pairs:)(\s)(\d+)';
$replacement = 'Wires: $m[3]/$m[7] Pairs: $m[3]';
$output = preg_replace_callback('/'.$pattern.'/',
function($m) {
global $replacement;
return $replacement;
},
$input);
echo $output;
I simply get
Wires: $m[3]/$m[7] Pairs: $m[3]