第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在文件中搜索字符串并替換該行中字符后面的所有內(nèi)容

在文件中搜索字符串并替換該行中字符后面的所有內(nèi)容

PHP
慕標(biāo)琳琳 2023-08-19 10:52:21
我希望使用 PHP 打開一個文件(參見下面的示例),逐行搜索字符串$colour并用.=$value之前的file.txt:red=0green=23blue=999yellow=44如果我的$value是"1"并且我的顏色是"blue",我的文件應(yīng)該更改為:red=0green=23blue=1yellow=44到目前為止我的代碼是:function write($colour, $value) {    $file = 'path';    $file_contents = file_get_contents($file);    $file_contents = str_replace($colour, $value, $file_contents);    file_put_contents($file, $file_contents);}然而,這只需要替換為$colour($value不是“=”之后的所有內(nèi)容),請參見下面的輸出:red=0green=231=999yellow=44我該怎么做呢?
查看完整描述

2 回答

?
滄海一幻覺

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個贊

問題是您只是將顏色文本替換為中的值

$file_contents = str_replace($colour, $value, $file_contents);

但這并不能取代整行。

使用preg_replace(),您可以替換以顏色開頭的內(nèi)容,然后=將其替換為...

$file_contents = preg_replace("/{$colour}=.*/", "{$colour}={$value}", $file_contents);


查看完整回答
反對 回復(fù) 2023-08-19
?
BIG陽

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個贊

發(fā)生這種情況是因?yàn)槟拇a僅用指定的值替換顏色。為此,您必須逐行加載文件,按 = 分解以分別獲得顏色和值,然后再次調(diào)整和存儲?;蛘呤褂谜齽t表達(dá)式。


我想提出不同的方法。而不是對作為字符串加載的文件進(jìn)行操作,而是將文件作為數(shù)組加載。有一個函數(shù)可以實(shí)現(xiàn)此目的:parse_ini_file。


<?php


// load the file to array with elements key => value

$data = parse_ini_file('conf.txt');


var_dump($data);


// change the data in array however you want - here i add 1 to red everytime this script is called, but it can be whatever: $data['red'] = 2; or similar

$data['red']++;


// now just build the contents of the file again and save it

$contents = '';

foreach ($data as $key => $value) {

  $contents .= $key.'='.$value.PHP_EOL;

}


file_put_contents('conf.txt', $contents);

結(jié)果:


// this is how the file looks like at start

cat conf.txt 

red=0

green=23

blue=1

yellow=44


// this is how $data looks

array(4) {

  ["red"]=>

  string(1) "0"

  ["green"]=>

  string(2) "23"

  ["blue"]=>

  string(1) "1"

  ["yellow"]=>

  string(2) "44"

}


// and the file after the execution

cat conf.txt 

red=1

green=23

blue=1

yellow=44

更改$data['red']++;為$data[$color] = $value;將其放入函數(shù)中即可。


查看完整回答
反對 回復(fù) 2023-08-19
  • 2 回答
  • 0 關(guān)注
  • 157 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號