dongxun4110 2014-03-16 18:38 采纳率: 0%
浏览 127
已采纳

使用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-.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制