[英]Find a string in a text file and add text at the beginning to that line in php
[英]How do I find the line in a text file beginning with 5678 and replace it with nothing using php?
可以說該文本文件包含:
56715:Jim:12/22/10:19
5678:Sara:9/04/08:92
53676:Mark:12/19/10:6
56797:Mike:12/04/10:123
5678:Sara:12/09/10:49
56479:Sammy:12/12/10:645
56580:Martha:12/19/10:952
我想找到以“ 5678”開頭的行,並將其替換為任何內容,因此該文件現在僅包含:
56715:Jim:12/22/10:19
53676:Mark:12/19/10:6
56797:Mike:12/04/10:123
56479:Sammy:12/12/10:645
56580:Martha:12/19/10:952
謝謝。
// The filename
$filename = 'filename.txt';
// Stores each line into an array item
$array = file($filename);
// Function to return true when a line does not start with 5678
function filter_start($item)
{
return !preg_match('/^5678:/', $item);
}
// Runs the array through the filter function
$new_array = array_filter($array, 'filter_start');
// Writes the changes back to the file
file_put_contents($filename, implode($new_array));
好吧,只需使用preg_replace:
$data = file_get_contents($filename);
$data = preg_replace('/^5678.*(\n|$)/m', '', $data);
注意m
修飾符。 這會將PCRE置於多行模式,其中^
匹配文檔的開頭,並且在任何換行符之后(而$
匹配文檔的結尾,並且在任何換行符之前)...
另外,根據您的確切需求,您可以創建一個流過濾器 :
class LineStartFilter extends php_user_filter {
protected $data = '';
protected $regex = '//';
public function filter($in, $out, &$consumed, $closing) {
var_dump($this->regex);
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = preg_replace($this->regex, '', $bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
public function onCreate() {
list($prefix, $data) = explode('.', $this->filtername);
$this->data = $data;
$this->regex = '/^'.preg_quote($data, '/').'.*(\n|$)/m';
}
}
stream_filter_register('linestartfilter.*', 'LineStartFilter');
然后,只需在要讀取文件時執行以下操作:
$f = fopen('test.txt', 'r');
stream_filter_append($f, 'linestartfilter.5678');
fpassthru($f);
fclose($f);
這將輸出您請求的字符串。 如果要寫入另一個文件(將其復制):
$f = fopen('test.txt', 'r');
stream_filter_append($f, 'linestartfilter.5678');
$dest = fopen('destination.txt', 'w');
stream_copy_to_stream($f, $dest);
fclose($f);
fclose($dest);
preg_replace('~5678:[^\\n]+?\\n~', '', $text);
如果您的文本以\\n
結尾,則首先轉換行尾。
蒂姆·庫珀 file()
Tim Cooper)剛剛提醒我 file()
做什么:)
$lines = file($filename);
$lines = preg_grep('/^5678/', $lines, PREG_GREP_INVERT);
$file = implode($lines);
file_put_contents($filename, $file);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.