dongxun4110
2014-03-16 18:38
浏览 112
已采纳

使用PHP将变量的正值更改为负值和反向.txt文件[关闭]

I have a .txt file with variables called: X,Y,Z. They are delimited by spaces or new lines. It looks like:

Y-3.165 X-25.221 M8

Z32.054

Z26.57 F500

Y0.0 F1000

Y160.8

X-20.254

What i need is to change positive values of X into negative and reverse (negative to positive). The problem is that variables aren't always single on a line, it may be 2 or 3 of them (like: Y-3.165 X-25.221 M8).

I think the algorythm is :

  1. if(found X) -> go ahead till the next space character or line end, recording the characters between X and space or EOL

  2. when having a string like X-0.94 -> delete "-" otherwise -> add "-" symbol between X and first number after it –

But I am not sure if I am on the right track or even how to do it. Can you guide me?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duancuan6466 2014-03-16 18:59
    已采纳

    Can do it in three steps:

    $content = file_get_contents('/path/to/your/file');
    
    $content = str_replace('X-', 'X+', $content);
    $content = preg_replace('/X(\d)/', 'X-$1', $content);
    $content = str_replace('X+', 'X', $content);
    
    file_put_contents('/path/to/your/file', $content);
    

    So you turn X- to X+, then change all the X followed by a number to X- and that number and after that strip the + from the X+. You have to do that step with the X+ because if you change X- to X immediately, it would get replaced when changing the X to X-.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题