2 回答

TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
這是一個快速的方法 if$find = "Hello";和$repl = "Changed";:
$result = preg_replace("/\[Line (\d+\].*?$find.*)/", "[$repl $1", file("lines.html"));
file_put_contents("lines.html", $result);
匹配[Line并捕獲一位或多位()數(shù)字\d+
然后是任何東西.*?,然后是$find字符串,然后是任何.*捕獲所有內(nèi)容的東西
替換為[ $repl和捕獲的內(nèi)容$1

TA貢獻(xiàn)1865條經(jīng)驗 獲得超7個贊
要更改任何內(nèi)容,您必須使用現(xiàn)有行和新更改的行編寫一個新文件。這是一個簡單的例子
// create a new output file
$out = fopen('test2.txt', 'w');
$input = file("lines.html");
$find = "Hello";
foreach($input as $key => $line){
$tmp = $line;
if(stristr($line, $find)){
$tmp = str_replace('[Line', '[Changed', $line);
// or if `[Line` can appear more than once in the line
//$tmp = substr_replace($line, '[Changed', 0, 5);
}
fwrite($out, $tmp);
}
fclose($out);
結(jié)果
[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World
- 2 回答
- 0 關(guān)注
- 140 瀏覽
添加回答
舉報