dongxun4110 2014-03-16 10: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 10: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-.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部