开发者

Php search replace interesting task

I have an interesting puzzle to solve. We have to convert the following variable using PHP find replace command

from:
$string = '
h= 1.00                h= 2.00  h= 3.50
W= 1.50                w= 3.00  w= 4.50
st=5000                st=6000  st=7000
';

to:
$string = '
A=1.00, B=2.00, C=3.50
A=1.50, B=3.00, C=4.50
A=5000, B=6000, C=7000
';

Meaning that nicely format the string data and sometimes the columns are only 2 but then sometimes the columns are 3, 4, 5 or even 10.

I need开发者_开发问答 PHP to do this for me but I don't know what code will be good for it.

May be preg_replace could be helpful but I am not sure.

Thanks for the help in advance...


You could use something simplistic like:

preg_match_all('/\w+=\s*([\d.]+).+\w+=\s*([\d.]+).+\w+=\s*([\d.]+)/',
     $input, $values, PREG_SET_ORDER);
print_r($values);

This will extract the data line-wise:

[0] => Array
    (
        [0] => h= 1.00                h= 2.00  h= 3.50
        [1] => 1.00
        [2] => 2.00
        [3] => 3.50
    )

Which is then easy to reformat and rename.

foreach ($values as $row) {
    array_shift($row);
    $output .= "A=$row[0], B=$row[1], C=$row[2]\n";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜